tags:

views:

432

answers:

1

If I have a template function, for example like this:

template<typename T>
void func(const std::vector<T>& v)

Is there any way I can determine within the function whether T is a pointer, or would I have to use another template function for this, ie:

template<typename T>
void func(const std::vector<T*>& v)

Thanks

+22  A: 

Indeed, templates can do that, with partial template specialization:

template<typename T>
struct is_pointer { static const bool value = false; };

template<typename T>
struct is_pointer<T*> { static const bool value = true; };

template<typename T>
void func(const std::vector<T>& v) {
    std::cout << "is it a pointer? " << is_pointer<T>::value << std::endl;
}

If in the function you do things only valid to pointers, you better use the method of a separate function though, since the compiler type-checks the function as a whole.

You should, however, use boost for this, it includes that too: http://www.boost.org/doc/libs/1_37_0/libs/type_traits/doc/html/boost_typetraits/reference/is_pointer.html

Johannes Schaub - litb
+1 this is the correct answer indeed :)
Robert Gould
Good answer thanks - Rob Stanley
Yup, good answer indeed, I can only add 1.
Andreas Magnusson
thanks folks :)
Johannes Schaub - litb