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

时间:2011-06-02 18:37:01

标签: c++ templates

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

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

1 个答案:

答案 0 :(得分:17)

我认为你想要从函数的type参数中删除指针。如果是这样,那么这就是你如何做到这一点,

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
}

其中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;
};

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