如何从模板中的指针获取类型? [英] How do i get type from pointer in a template?

查看:258
本文介绍了如何从模板中的指针获取类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道如何写东西,但我确定有一个标准的方式传递的东西像 func< TheType *>()并使用模板魔术提取TheType以在您的代码中使用(也许TheType :: SomeStaticCall)。

I know how to write something up but i am sure there is a standard way of passing in something like func<TheType*>() and using template magic to extract TheType for use in your code (maybe TheType::SomeStaticCall).

当传入ptr时,标准方式/函数是什么? p>

What is the standard way/function to get that type when a ptr is passed in?

推荐答案

我想你要从函数的类型参数中删除指针。如果是这样,那么这里是如何做到这一点,

I think you want to remove the pointer-ness from the type argument to the function. If so, then here is how you can do this,

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

In C++0x, remove_pointer is defined in <type_traits> header file. But in C++03, you've to define it yourself.

这篇关于如何从模板中的指针获取类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆