New features in C++11 (15) - initializer_list parameter

Variable parameters in C language


In the programming process, there are often situations where you want the parameters of the function to be variable. One of the most common examples is the magical printf function, which can adjust the number of parameters according to the user's needs. In fact, we can also design variadic functions ourselves. For example, the following function can determine the number of input parameters based on the first parameter.


int  test( int  num,  ...) 
{ int i, result = 0 ; va_list parlist; va_start (parlist, num); // prepare the parameter list for (i = 0 ; i < num; i++) { // get each parameters, the type is determined by the second parameter of av_arg printf( "%d\n" , va_arg (parlist, int )); } va_end (parlist); //Close the parameter list return result; }
   

   

   

   

   

       

       
 
   

   

   


The number of subsequent parameters of test is determined by the first parameter number. With such a test function, the number of parameters can be determined as needed. The following code works fine:


test(2,10,20);  
test(4,1,2,3,4);    


Variadic in C++11


C++11 provides the initializer_list class in the standard library to handle cases where the number of arguments is variable but the types are the same. The most common way to use an initializer_list is to initialize it with a brace-enclosed list of values:


initializer_list<int> vlist{9,8,7,6};   


It can be used like a normal list, except that the value in vlist cannot be modified.


Continue to look at the following function:


template<typenameT>voidoutput(initializer_list<T>lst){for(auto&a:lst){cout<<a<<endl;}} 


   

       

   


This function is very simple, it just outputs the content in the list, it has several features:


  1. Through the use of templates, the use of auto is that it can automatically adapt to the type of the parameter

  2. Through the use of initializer_list, the number of parameters is automatically adapted.


After the function is done, how to use it depends on the mood.


initializer_list<int> vlist{9, 8, 7, 6};
output(vlist);

output({1, 3, 4, 5});

output({"How", "are", "you", "!"});


作者观点


有点意思吧。


觉得本文有帮助?请分享给更多人!
阅读更多更新文章,请扫描下面二维码,关注微信公众号【面向对象思考】

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325937249&siteId=291194637