The concept of uniform initialization appears in C++11:
int a1 = {1 };// ok int a2 = {1.0 }; // error, must shrink convert int array1[] = {1 , 2 , 3 , 4 }; // ok int arrya2[] = {1.0 , 2.0 , 3.0 , 4.0 };// ok
Note The A2 initialization error and the correct contrast of the array2. On the one hand uniform initialization require the type of initialization to be consistent, but the new C + + standard must be compatible with c++98, and array2 initialization in c++98 is legal.
The new C++11 standard also adds a std::initializer_list<> class that can be passed in the constructor for this parameter type
#include <iostream>classa{A (int,int) {Std::cout<<"Int,int"<<Std::endl;} A (Std::initializer_list<int>)//note is not a reference! {Std::cout<<"initializer_list<int>"<<Std::endl;}};intMain () {A A1 (1,1);//int intA a2{1,1};//initializer_list<int>A A3 = {1,1};//initializer_list<int>return 0;}
Notice that A3 is calling the initializer_list<int> version of the constructor.
#include <iostream>classa{ExplicitAint,int) {Std::cout<<"Int,int"<<Std::endl;} A (Std::initializer_list<int>)//Note not a reference! {std::cout<<"initializer_list<int>"<<Std::endl;}};classb{B (int,int) {Std::cout<<"Int,int"<<Std::endl;} ExplicitB (std::initializer_list<int>)//Note not a reference! {std::cout<<"initializer_list<int>"<<Std::endl;}};classc{ExplicitCint,int) {Std::cout<<"Int,int"<<Std::endl;} ExplicitC (std::initializer_list<int>)//Note not a reference! {std::cout<<"initializer_list<int>"<<Std::endl;}};intMain () {a A= {1,1};//initializer_list<int>b b = {1,1};//Int,intc C = {1,1};//error: cannot be from initializer_list to Creturn 0;}
The constructor for B above because the Initializer_list version is set to explicit and the constructor becomes the version of B (Int,int), we can infer:
1.initializer_list priority is higher than the constructor for the specified parameter
2.uniform initialization actually passed a Initializer_list object to the constructor, and a series of implicit conversions occurred. (the error message can be judged by the constructor of Class C)
——————————————————————————————————————————————————————————————————————
Reference: "C + + standard library-self-study tutorials and reference manual" Nicolai M.josuttis second Edition
C++11 in uniform initialization and initializer_list