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

How do i get type from pointer in a template?

本文关键字:指针 获取 取类型      更新时间:2023-10-16

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

传入ptr时,获取该类型的标准方法/函数是什么?

我认为您希望删除函数的类型参数中的指针ness。如果是这样的话,那么,你可以这样做

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