c++ - 没有默认构造函数的模板的模板

标签 c++ templates

我正在尝试编写一个没有默认构造函数的模板类。
对于 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)必须默认构造 x在调用之前 operator=复制分配 y

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

你的构造函数应该是

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

关于c++ - 没有默认构造函数的模板的模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35261448/

相关文章:

javascript - 使用下划线模板构建数独板

C++ 模板函数优先级

c++ - 使用 std::remove_if() 时没有可行的重载 '='

c++ - 为什么简单的 C++ vector 函数会产生下标越界?

c++ - 使用 QCPItemTracer 在 QCustomPlot 中显示点

c++ - POSIX 共享内存写入/读取

c++ - 使用常量变量作为数组的大小

c++ - 通过引入不相关的调用运算符奇怪地解决了模棱两可的调用运算符重载 - clang vs gcc

C++ 向数组添加元素

c++ - 委托(delegate)给另一个对象的运算符(operator)->