How do i get type from pointer in a template?
Asked Answered
S

2

10

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).

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

Strepitous answered 2/6, 2011 at 18:37 Comment(2)
You should add some code to make the question clear. What is it that you want to do, what are the inputs?Aponte
@David: I had something but had the oversight of not realizing it was be filter out as a tag (and not show up). Does it make since ATM?Strepitous
M
20

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.

Millimeter answered 2/6, 2011 at 18:50 Comment(6)
so remove_pointer isnt in the std? This is exactly what i wanted but my gut says theres something in stl i can use (but maybe not?)Strepitous
@acidzombie24: In C++0x, Yes. In C++03, No.Millimeter
darn, what is it in C++0x? (header and i guess the struct name if not the same) I guess i was half right?Strepitous
@acidzombie24: C++0x = incoming version of C++ :PMillimeter
For C++03 it's in TR1 and Boost.TypeTraitsPompey
Very nice indeed, although I think the C++0x remove_pointer only removes one pointer at a time.Groundsheet
A
0

If you just want to remove one level of pointer and get the actual type of the pointee, that is it T is int** want to get int* instead of int you could perhaps work with decltype, but that requires you to be able to construct an expression of type T (which is to be dereferenced) is actually a pointer that shouldbe possible using reinterpret_cast if T is a pointer. So it boils down to something like:

std::remove_reference_t<decltype(*reinterpret_cast<T>(NULL))>
Allyce answered 27/8, 2024 at 9:45 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.