如何从不透明指针typedef创建shared_ptr?(或:我如何"解包"typedef?)

ipm*_*mcc 15 c++

如果你有一个不透明的指针typedef,有没有办法动态引用指向的类型,比如说,在模板中使用?例如,假设你有这样的事情:

struct Foo; // Forward declared struct
typedef Foo* FooPtr; // Opaque pointer
Run Code Online (Sandbox Code Playgroud)

因为智能指针类型是指针类型的模板,为了定义std::shared_ptr它,你似乎必须说:

std::shared_ptr<struct Foo> theSharedPtr;
Run Code Online (Sandbox Code Playgroud)

有没有办法定义这样的指针而不"手动"展开不透明指针typedef?我觉得我必须在这里遗漏一些明显的东西,但你可能会想到这样的东西(注意:这些不起作用):

std::shared_ptr<*FooPtr> theSharedPointer;
// or
std::shared_ptr<pointedto(FooPtr)> theSharedPointer;
Run Code Online (Sandbox Code Playgroud)

我觉得这应该是可能的.我错过了什么吗?我觉得这是一个即将来临的前额...

编辑:在一些更多的Noodling,似乎,在通常情况下,shared_ptr<T>想要采取sizeof(T).你可以通过为构造函数提供一个删除器来解决这个问题.我怀疑这使得这有点像一个边缘情况,但它仍然似乎与C++中的所有类型争论,我应该能够"解包"一个指针类型,而不是手动这样做.

sba*_*bbi 23

在C++ 11中:

#include <type_traits>

typedef std::shared_ptr< std::remove_pointer< FooPtr >::type > theSharedPtr;
Run Code Online (Sandbox Code Playgroud)

在C++ 03中,您可以使用boost::remove_pointer完全相同的方式.

如果您不想包含boost,则编写remove_pointer元函数非常简单:

template<class T> struct remove_pointer;
template<class T> struct remove_pointer<T*> { typedef T type; };
Run Code Online (Sandbox Code Playgroud)

  • 好吧,考虑到你正在使用std :: shared_ptr显然你在C++ 11中...我还是会在这里留下我的其余答案. (2认同)

Sho*_*hoe 5

是的,因为您已经在使用C++ 11功能,所以可以使用类型特征来执行此操作.具体通过使用std::remove_pointer:

std::remove_pointer<Foo*>::type; // Foo
Run Code Online (Sandbox Code Playgroud)

当然,您需要包含特定的标准标题,即:

#include <type_traits>
Run Code Online (Sandbox Code Playgroud)

使用它.