Reputation: 5784
I'm trying to write a template class that doesn't have default constructor.
For A<int>
works fine, but for A<A<int>>
I don't know how to get it to work.
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 }
Error list from 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 {
^
Upvotes: 0
Views: 436
Reputation: 133609
You are not properly constructing x
in the initializer list of the constructor, hence A(T y)
must default construct x
before invoking operator=
to copy assign y
to it.
int
provides a default constructor, which just let the value uninitialized, but A<int>
does not.
Your constructor should be
A(T y) : x(y) { }
Upvotes: 3