gpt4 book ai didi

c++ - 我如何从模板中的指针获取类型?

转载 作者:可可西里 更新时间:2023-11-01 18:15:18 25 4
gpt4 key购买 nike

我知道如何写一些东西,但我确信有一种标准的方式可以传递类似 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com