I passed an nested braced-init-lists to class constructor:
#include <iostream>
#include <type_traits>
#include <variant>
#include <vector>
class NestedInteger final {
public:
NestedInteger(int i) : type_(INT), val_int_(i) {}
// NestedInteger(std::initializer_list<NestedInteger> ni) {
template <typename T>
NestedInteger(std::initializer_list<T> ni) {
for (auto it = ni.begin(); it != ni.end(); it++) {
val_vec_.push_back(*it);
}
}
private:
enum { INT, VECTOR } type_;
int val_int_;
std::vector<NestedInteger> val_vec_;
};
int main() {
NestedInteger ni1{1};
NestedInteger ni2{1, 2, 3};
NestedInteger ni3{{1}, 2, 3};
NestedInteger ni4{{1, 2, 3}};
NestedInteger ni5{{1, 2, 3}, {4, 5, 6, 7}};
return 0;
}
And I got compilation error:
t.cpp:29:44: error: no matching function for call to ‘NestedInteger::NestedInteger(<brace-enclosed initializer list>)’
29 | NestedInteger ni5{{1, 2, 3}, {4, 5, 6, 7}};
| ^
t.cpp:12:3: note: candidate: ‘template<class T> NestedInteger::NestedInteger(std::initializer_list<_Tp>)’
12 | NestedInteger(std::initializer_list<T> ni) {
| ^~~~~~~~~~~~~
t.cpp:12:3: note: template argument deduction/substitution failed:
t.cpp:29:44: note: candidate expects 1 argument, 2 provided
29 | NestedInteger ni5{{1, 2, 3}, {4, 5, 6, 7}};
...
I read the list initialization in cppreference here. And I can tell the expression belongs to the first syntax type:
T object { arg1, arg2, ... }; (1)
initialization of a named variable with a braced-init-list (that is, a possibly empty brace-enclosed list of expressions or nested braced-init-lists)
I can't understand the explanation about the effects.
Could you help to figure out:
Which item in the explanation does this case match?
Is this a non-deduced contexts described here?
By the way, if I change the template to specific type as the commented line, the compilation error disapeared.