没有默认构造函数的模板的模板

template of template without default constructor

本文关键字:构造函数 默认      更新时间:2023-10-16

>我正在尝试编写一个没有默认构造函数的模板类。
对于A<int>工作正常,但对于A<A<int>>我不知道如何让它工作。

  1   #include <iostream>
  2   using namespace std;
  3 
  4   template <typename T>
  5   class A {
  6     T x;
  7 
  8    public:
  9     A(T y) { x = y; }
 10   };
 11 
 12   int main() {
 13     A<int> a(0);
 14     A<A<int> > b(A<int>(0));
 15 
 16     return 0;
 17   }

来自 clang 的错误列表

    test.cpp:9:5: error: constructor for 'A<A<int> >' must explicitly initialize the member 'x' which does not have a default constructor
        A(T y) { x = y; }
        ^
    test.cpp:14:16: note: in instantiation of member function 'A<A<int> >::A' requested here
        A<A<int> > b(A<int>(0));
                   ^
    test.cpp:6:7: note: member is declared here
        T x;
          ^
    test.cpp:5:9: note: 'A<int>' declared here
      class A {
            ^

您没有在构造函数的初始值设定项列表中正确构造x,因此A(T y)必须在调用operator=之前默认构造x以将赋y复制到它。

int提供了一个默认构造函数,它只允许值未初始化,但A<int>没有。

您的构造函数应该是

A(T y) : x(y) { }