简体   繁体   English

C ++中模板的部分专业化

[英]partial specialization of the templates in c++

is it possible to do in c++ something like that: 是否可以在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;

};

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 实际上,我想知道是否可以实现模板重载,当两个类在模板中具有相同的名称但参数不同时,请先感谢任何好主意

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. 当然,为了安全起见,您需要A<T1*, T2*>的第三个。 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 : 如果您想知道没有指针的类型,可以使用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: 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;
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM