How do i get type from pointer in a template?
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 f开发者_JS百科or use in your code (maybe TheType::SomeStaticCall).
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
}
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.
精彩评论