我知道如何写东西,但是我确定有一种标准方法可以传递诸如func<TheType*>()之类的东西,并使用模板魔术来提取TheType以便在您的代码中使用(也许是TheType::SomeStaticCall)。

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

最佳答案

我认为您想从函数的类型参数中删除指针性。如果是这样,那么您可以按照以下方法进行操作,

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中,您必须自己定义它。

关于c++ - 如何从模板中的指针获取类型?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/6218813/

10-11 22:36
查看更多