Reputation:
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?
Upvotes: 10
Views: 6179
Reputation: 14400
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))>
Upvotes: 0
Reputation: 361802
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.
Upvotes: 21