如何从模板中的指针获取类型?

7 c++ templates

我知道如何编写一些东西,但我确信有一种传递类似的标准方法,func<TheType*>()并使用模板魔法来提取在代码中使用的TheType(可能是TheType :: SomeStaticCall).

传入ptr时获取该类型的标准方式/功能是什么?

Naw*_*waz 17

我想你想从函数的类型参数中删除指针.如果是这样,那么这就是你如何做到这一点,

template<typename T>
void func()
{
    typename remove_pointer<T>::type type;
    //you can use `type` which is free from pointer-ness

    //if T = int*, then type = int
    //if T = int****, then type = int 
    //if T = vector<int>, then type = vector<int>
    //if T = vector<int>*, then type = vector<int>
    //if T = vector<int>**, then type = vector<int>
    //that is, type is always free from pointer-ness
}
Run Code Online (Sandbox Code Playgroud)

其中remove_pointer定义为:

template<typename T>
struct remove_pointer
{
    typedef T type;
};

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

在C++ 0x中,remove_pointer<type_traits>头文件中定义.但是在C++ 03中,你要自己定义它.

  • 非常好,虽然我认为C++ 0x remove_pointer一次只删除一个指针. (7认同)