46

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

1

3 Answers 3

99

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

5
  • What a lonely little answer you've got here. :)
    – GManNickG
    Jan 29, 2011 at 23:42
  • @GMan haha :) How did you hit this old answer of me xD Jan 30, 2011 at 0:17
  • @Johannes: Meh, I remembered you were abnormally high on the templates tag top rep. list, so I wanted to see why. :)
    – GManNickG
    Jan 30, 2011 at 5:01
  • +1 Some answers never get old, Johannes. This is one such answer.
    – WhozCraig
    Aug 15, 2013 at 6:54
  • 2
    @WhozCraig Actually this answer did get old, because for C++ 11 this other answer is better stackoverflow.com/a/15974269/55721
    – dss539
    Mar 19, 2015 at 15:55
68

C++ 11 has a nice little pointer check function built in: std::is_pointer<T>::value

This returns a boolean bool value.

From http://en.cppreference.com/w/cpp/types/is_pointer

#include <iostream>
#include <type_traits>

class A {};

int main() 
{
    std::cout << std::boolalpha;
    std::cout << std::is_pointer<A>::value << '\n';
    std::cout << std::is_pointer<A*>::value << '\n';
    std::cout << std::is_pointer<float>::value << '\n';
    std::cout << std::is_pointer<int>::value << '\n';
    std::cout << std::is_pointer<int*>::value << '\n';
    std::cout << std::is_pointer<int**>::value << '\n';
}
2

From C++17, there is an even shorter built-in construct, std::is_pointer_v<T>:

#include <type_traits>
 
int main()
{
    class A {};
 
    static_assert(
           not std::is_pointer<A>::value
        && not std::is_pointer_v<A>); // equivalent to above, but shorter

    return 0;
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.