fuenfundachtzig
fuenfundachtzig

Reputation: 8352

Templated class function T: How to find out if T is a pointer?

As a follow-up to this question: I need to decide in a class function like this:

template< typename T > bool Class::Fun <T*> ( T& variable ) {...}

whether T is a pointer or not.

In the question cited above the answer was to use partial template specialization. As far as I've found out this is not possible for class functions. Is this true? If so, is there another way of finding out if T is a pointer?

Upvotes: 5

Views: 1435

Answers (3)

Kirill V. Lyadvinsky
Kirill V. Lyadvinsky

Reputation: 99565

No need to specialize member function. In that answer used stand-alone structure. You're still free to use it in class member functions.

// stand-alone helper struct
template<typename T>
struct is_pointer { static const bool value = false; };    
template<typename T>
struct is_pointer<T*> { static const bool value = true; };

// your class
class Class{
public:
 template<typename T>
 void Fun(T& variable) {
     std::cout << "is it a pointer? " << is_pointer<T>::value << std::endl;
 }
};

On the other hand, you could overload function:

class Class {
public:
 template<typename T>
 void Fun(T& variable) {
     std::cout << "is it not a pointer! " << std::endl;
 }
 template<typename T>
 void Fun(T*& variable) {
     std::cout << "is it a pointer! " << std::endl;
 }
};

Upvotes: 22

gimpf
gimpf

Reputation: 4511

Have a look at Boost.TypeTraits, together with Boost EnableIf.

Upvotes: 3

moonshadow
moonshadow

Reputation: 89055

Take a look at boost::is_pointer.

Upvotes: 8

Related Questions