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 h开发者_运维技巧ave the same name but different arguments in template, thanks in advance for any good idea
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.
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;
};
精彩评论