Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 745
fuenfundachtzig Avatar asked Sep 11 '09 19:09

fuenfundachtzig


1 Answers

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;
 }
};
like image 187
Kirill V. Lyadvinsky Avatar answered Sep 28 '22 13:09

Kirill V. Lyadvinsky