如何从模板中的指针获取类型
How do i get type from pointer in a template?
我知道如何写一些东西,但我相信有一种标准的方法可以传入类似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中,你必须自己定义它。
相关文章:
- 我可以使用 decltype() 或其他东西通过指针获取真实类型吗?
- 通过基类指针获取派生类对象的引用
- C++从双指针获取数据
- 如何从原始指针获取shared_ptr?
- 如何从C++中的字符指针获取子字符串
- 使用 std::launder 从指向非活动工会成员的指针获取指向活动工会成员的指针?
- 使用我的共享指针获取内存泄漏
- 通过指向非多态类型的基类的指针获取已分配内存的地址
- 指向引用的指针获取器
- 使用 std::launder 从指向非活动对象的指针获取指向活动对象成员的指针?
- CPP:无法使用 -> 通过指针获取成员的值
- 字符串十六进制到指针获取值
- 从基类指针获取模板派生类的值
- 从 C++ 数组元素的指针获取索引的最快方法是什么
- 通过指针获取最大数量的元素
- 如何使用指针获取字符串数据
- 返回指向指针数组的指针获取下一个元素失败
- 从"子项"项指针获取"父""std::tuple"
- 从成员函数指针获取方法的返回类型
- 如何从指向数组的指针获取对该数组的引用