C++模板构造函数的特化

use*_*536 8 c++ templates constructor specialization

我有一个模板化的类A <T,int>和两个typedef A <string,20>和A <string,30>.如何覆盖A <string,20>的构造函数?以下不起作用:

template <typename T, int M> class A;
typedef  A<std::string, 20> one_type;
typedef  A<std::string, 30> second_type;


template <typename T, int M>
class A {
public:
  A(int m) {test= (m>M);}

  bool test;

};


template<>
one_type::one_type() { cerr << "One type" << endl;}
Run Code Online (Sandbox Code Playgroud)

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

Mar*_*zek 13

迟到但非常优雅的解决方案:C++ 2020 引入了Constraints and Concepts。您现在可以有条件地启用和禁用构造函数和析构函数!

#include <iostream>
#include <type_traits>

template<class T>
struct constructor_specialized
{
    constructor_specialized() requires(std::is_same_v<T, int>)
    {
        std::cout << "Specialized Constructor\n";
    };

    constructor_specialized()
    {
        std::cout << "Generic Constructor\n";
    };
};

int main()
{
    constructor_specialized<int> int_constructor;
    constructor_specialized<float> float_constructor;
};
Run Code Online (Sandbox Code Playgroud)

运行此处的代码。


xto*_*ofl 10

你唯一不能做的就是使用它typedef来定义构造函数.除此之外,你应该专门A<string,20>构建这样的构造函数:

template<> A<string,20>::A(int){}
Run Code Online (Sandbox Code Playgroud)

如果你想A<string,20>拥有一个不同于泛型的构造函数A,你需要专门化整个A<string,20>类:

template<> class A<string,20> {
public:
   A(const string& takethistwentytimes) { cerr << "One Type" << std::endl; }
};
Run Code Online (Sandbox Code Playgroud)


seh*_*seh 7

假设你真的意味着A::test要公开访问,你可以这样做:

#include <iostream>


template <int M>
struct ABase
{
  ABase(int n) : test_( n > M )
  {}

  bool const test_;
};


template <typename T, int M>
struct A : ABase<M>
{
  A(int n) : ABase<M>(n)
  {}
};


template <typename T>
A<T, 20>::A(int n)
  : ABase<20>(n)
  { std::cerr << "One type" << std::endl; }
Run Code Online (Sandbox Code Playgroud)

踢轮胎:

int main(int argc, char* argv[])
{
  A<int, 20> a(19);
  std::cout << "a:" << a.test_ << std::endl;
  A<int, 30> b(31);
  std::cout << "b:" << b.test_ << std::endl;
  return 0;
}
Run Code Online (Sandbox Code Playgroud)


Fra*_*nov 1

您目前的方法无法做到这一点。one_type 是特定模板专业化的别名,因此它获取模板具有的任何代码。

如果要添加特定于 one_type 的代码,则必须将其声明为 A 专业化的子类,如下所示:

  class one_type:
    public A<std::string, 20>
  {
    one_type(int m)
      : A<str::string, 20>(m)
    {
      cerr << "One type" << endl;
    }
  };
Run Code Online (Sandbox Code Playgroud)