classT { public: T(int a, int b) {std::cout << "a, b" << std::endl;} T(std::initializer_list<int> list) {std::cout << "initializer-list" << std::endl;} explicitT(int a, int b, int c){std::cout << "explicit a, b, c" << std::endl;} };
voidfun(const T& t){}
intmain() { T t{1,2,3}; //调用T(std::initializer_list<int> list) T t1 = {1,2,3}; fun({1,2,3}); return0; }
运行结果:
1 2 3 4 5 6 7
main.cpp: In function'int main()': main.cpp:19:4: warning: variable 't1'set but not used [-Wunused-but-set-variable] T t1 = {1,2,3}; ^~ initializer-list initializer-list initializer-list
和预期一样, 只要存在接收initializer-list为参数的构造器, 就直接使用它, 所以不会去调用explicit T(int a, int b, int c).
但是一旦当你取消了T(std::initializer_list<int> list)这个构造器, 那么编译器会自动拆分大括号的参数, 去调用explicit T(int a, int b, int c), 结果就报错了:
1 2 3 4 5 6 7 8
main.cpp: In function'int main()': main.cpp:19:15: error: converting to 'T' from initializer list would use explicit constructor 'T::T(int, int, int)' T t1 = {1,2,3}; ^ main.cpp:20:13: error: converting to 'const T' from initializer list would use explicit constructor 'T::T(int, int, int)' fun({1,2,3});