测试传递给函数的void*是shared_ptr还是unique_ptr

Fra*_*ler 0 c++ smart-pointers void-pointers reinterpret-cast

我正在为类创建一个函数,并且参数被声明为void*但是在我需要测试的函数中,如果这个void*是shared_ptr还是unique_ptr,是否有办法测试这种情况?

这就是我到目前为止所做的工作; 我的类是模板类型,不存储任何成员变量.它有一个默认的构造函数,它也可以通过传入一个shared_ptr<Type>或一个来构造,unique_ptr<Type>并且它具有多个allocate()函数,它们执行相同类型的工作.

#ifndef ALLOCATOR_H
#define ALLOCATOR_H

#include <memory>
#include <iostream>

template<class Type>
class Allocator {
public:
    Allocator(){}
    Allocator( Type type, void* pPtr );
    Allocator( std::shared_ptr<Type>& pType );
    Allocator( std::unique_ptr<Type>& pType );
    // ~Allocator(); // Default Okay

    void allocate( std::shared_ptr<Type>& pType );
    void allocate( std::unique_ptr<Type>& pType );
    void allocate( Type type, void* pPtr );

private:
    Allocator( const Allocator& c ); // Not Implemented
    Allocator& operator=( const Allocator& c ); // Not Implemented

}; // Allocator

#include "Allocator.inl"

#endif // ALLOCATOR_H
Run Code Online (Sandbox Code Playgroud)

我的*.cpp文件只有#include "Allocator.h"所有的实现都在我的*.inl文件中.

我的两个构造函数:Allocator( std::shared_ptr<Type>& pType );&Allocator( std::unique_ptr<Type>& pType );以及两个匹配allocate()函数都可以正常工作.构造Allocator( Type type, void* pPtr );函数及其匹配函数是我遇到麻烦的地方.

构造函数本身是直截了当的,因为它所做的就是调用匹配函数向它传递变量.

template<class Type>
Allocator<Type>::Allocator( Type type, void* pPtr ) {
    allocate( type, eType, pPtr );
}
Run Code Online (Sandbox Code Playgroud)

它正在我正在努力的功能实现中.

template<class Type>
void Allocator<Type>::allocate( Type type, void* pData ) {
    if ( pData == reinterpret_cast<void*>( std::shared_ptr<Type ) ) {
        std::shared_ptr<Type> pShared;
        pShared.reset( new Type( type ) );
        pData = reinterpret_cast<void*>( pShared );

    } else if ( pData == reinterpret_cast<void*>( std::unique_ptr<Type ) ) {
        std::unique_ptr<Type> pUnique;
        pUnique.reset( new Type( type ) );
        pData = reinterpret_cast<void*>( pUnique );

    } else {
        std::cout << "Error invalid pointer type passed in << std::endl
                  << "must be either a std::shared_ptr<Type> << std::endl
                  << "or a std::unique_ptr<Type> << std::endl;
    }            
}
Run Code Online (Sandbox Code Playgroud)

除了检查void*传入是否是我可能会std::shared_ptr<Type>遇到std::unique_ptr<Type>的其他问题之外,我是否使用reinterpret_cast<void*>正确的方法将智能指针转换为无效指针,如果不是,如何实现?

Bar*_*rry 8

你无法检查是什么类型的void*.这是一个void*.而已.它不像是boost::any在巧妙地隐藏其他类型的信息.这只是 void*.你无法检查它来自哪种类型.您无法测试它是否来自特定类型.你没有信息.压缩.纳达.小人物.虚空.

  • @FrancisCugler你应该实际传递智能指针 - 而不是`void*`.如果您确实需要,请不要将类型信息丢弃在地板上! (2认同)