rookie
rookie

Reputation: 7883

partial specialization of the templates in c++

is it possible to do in c++ something like that:

template<class T1, class T2>
  class A<T1*, T2> {
    T1* var;
    T2 var1;

};

template<class T1, class T2>
  class A<T1, T2*> {
    T1 var;
    T2* var1;

};

Actually I want to know if I can reach template overloading, when two classes have the same name but different arguments in template, thanks in advance for any good idea

Upvotes: 2

Views: 218

Answers (2)

Pawel Zubrycki
Pawel Zubrycki

Reputation: 2713

If you want to know the type without pointer you can use boost::type_traits:

#include <boost/type_traits.hpp>

template<class T1, class T2>
class A {
  typedef boost::remove_pointer<T1>::type T1_type;
  typedef boost::remove_pointer<T2>::type T2_type;
  T1_type *var;
  T2_type *var1;
};

remove_pointer template is easy to write on your own:

template<class T> 
struct remove_pointer{
  typedef T type;
};

template<class T>
struct remove_pointer<T*>{
  typedef T type; 
  //or even 
  typedef remove_pointer<T>::type type;
};

Upvotes: 1

Johannes Schaub - litb
Johannes Schaub - litb

Reputation: 507343

That's known as partial template specialization

template<class T1, class T2>
class A;

template<class T1, class T2>
class A<T1*, T2> {
    T1* var;
    T2 var1;
};

template<class T1, class T2>
class A<T1, T2*> {
    T1 var;
    T2* var1;
};

Of course, you need a third one for A<T1*, T2*> to play safe. Otherwise you will get an ambiguity of both are pointers.

Upvotes: 6

Related Questions