I'm using initializer lists for structs. But, it doesn't work with inheritance.
This code is good.
struct K {
int x, y;
};
K k {1, 2};
But, this produces an error.
struct L : public K {};
L l {1, 2};
Also, this does not work.
struct X {
int x;
};
struct Y : public X {
int y;
};
Y y {1, 2};
Is there a way to use initializer lists with inherited structs. I'm using them in templates and so it doesn't compile if it is an inherited class or not.
Your code would work with C++17. Since C++17 both L
and Y
are considered as aggregate type:
no
virtual, private, or protected (since C++17)
base classes
Then brace elision is allowed; i.e. the braces around nested initializer lists for subaggregate could be elided and then you can just write L l {1, 2};
and Y y {1, 2};
(instead of L l {{1, 2}};
and Y y {{1}, 2};
).
If the aggregate initialization uses
copy- (until C++14)
list-initialization syntax (T a = {args..}or T a {args..} (since C++14)
), the braces around the nested initializer lists may be elided (omitted), in which case as many initializer clauses as necessary are used to initialize every member or element of the corresponding subaggregate, and the subsequent initializer clauses are used to initialize the following members of the object.
Before C++17 it doesn't work because list initialization is performed instead, the appropriate constructors are tried to be used and fails.