是否可以用c ++这样做:
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;
};
实际上我想知道我是否可以达到模板重载,当两个类具有相同名称但模板中的参数不同时,提前感谢任何好主意
答案 0 :(得分:6)
这就是所谓的部分模板专业化
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;
};
当然,A<T1*, T2*>
需要第三个才能安全玩耍。否则你会得到两个指针的含糊不清。
答案 1 :(得分:1)
如果您想知道没有指针的类型,可以使用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<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;
};