c++提取指针的类型

C++ extract type of pointer

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

假设我有

typedef T* PtrType;

是否有办法从PtrType中提取T类型?

std::remove_pointer<PtrType>::type

如果T是模板参数,则必须使用:

typename std::remove_pointer<PtrType>::type

在c++ 11中,您可以使用std::remove_pointer:

std::remove_pointer<PtrType>::type

如果没有c++ 11,你可以自己简单地实现它:

template <class T>
struct remove_pointer;
template <class U>
struct remove_pointer<U*>
{
  typedef U type;
};

如果T确实是一个指针,上面的代码会从T中移除一个指针,否则会导致编译错误。如果您想完全匹配std::remove_pointer的功能,那么您也可以提供默认的大小写:

template <class T>
struct remove_pointer
{
  typedef T type;
};
// Partial specialisation for U* same as before