How do i get type from pointer in a template?

前端 未结 1 639
一向
一向 2021-01-12 06:27

I know how to write something up but i am sure there is a standard way of passing in something like func() and using template magic to extract T

相关标签:
1条回答
  • 2021-01-12 07:17

    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
    }
    

    where remove_pointer is defined as:

    template<typename T>
    struct remove_pointer
    {
        typedef T type;
    };
    
    template<typename T>
    struct remove_pointer<T*>
    {
        typedef typename remove_pointer<T>::type type;
    };
    

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

    0 讨论(0)
提交回复
热议问题