C模板特化的构造函数

前端之家收集整理的这篇文章主要介绍了C模板特化的构造函数前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一个模板化的类A< T,int>和两个typedef A< string,20>和A< string,30>.
如何覆盖A< string,20>的构造函数? ?以下不起作用:
  1. template <typename T,int M> class A;
  2. typedef A<std::string,20> one_type;
  3. typedef A<std::string,30> second_type;
  4.  
  5.  
  6. template <typename T,int M>
  7. class A {
  8. public:
  9. A(int m) {test= (m>M);}
  10.  
  11. bool test;
  12.  
  13. };
  14.  
  15.  
  16. template<>
  17. one_type::one_type() { cerr << "One type" << endl;}

我想要A< std :: string,20>类;做一些其他课没有做的事.如何在不更改构造函数的情况下执行此操作A:A(int)?

解决方法

您唯一不能做的是使用typedef来定义构造函数.除此之外,你应该专门化A< string,20>像这样的构造函数
  1. template<> A<string,20>::A(int){}

如果你想要A< string,20>要使用与通用A不同的构造函数,您需要专门化整个A< string,20>类:

  1. template<> class A<string,20> {
  2. public:
  3. A( const string& takethistwentytimes ) { cerr << "One Type" << std::endl; }
  4. };

猜你在找的C&C++相关文章