Before start of this topic please go through uniform initialization.
std::initializer_list
In c++, we treat all data type on same level, we can initialize build-in data using new initialization called as uniform intialization so this new initialization must be handled for user defined data type also. This functionalities will be taken care by new constructor called as “initializer-list constructor”
std::initializer_list<> is a class template. It will be used as parameter in “initializer-list constructor” and function that is handling uniform initialization.
source code with example:
/* Program: std::initializer_list Author: Alpha Master Date: 8 March 2021 */ //Header File #include<iostream> #include<vector> // class with initializer-list constructor class test { int m_i; public: test(const std::initializer_list<int>& list) { for(const auto& ele : list) { m_i = ele; } } int getVal(){return m_i;} }; //Function with std::initializer_list<> void func(std::initializer_list<int> list) { for(auto ele: list) { std::cout<<ele<<" "; } std::cout<<std::endl; } int main() { std::cout<<"Initialization list"<<std::endl; //Interger int i_val01{1}; std::cout<<"i_val01:"<<i_val01<<std::endl; //Float float f_val01{1.1}; std::cout<<"f_val01:"<<f_val01<<std::endl; //User defined object test obj{1}; std::cout<<"class member value:"<<obj.getVal()<<std::endl; //Function func({1,2,3}); return 0; }
Output:
Initialization list i_val01:1 f_val01:1.1 class member value:1 1 2 3