Functions with deformable parameters

Sometimes we want to pass actual parameters to the function, but the number of actual parameters is unpredictable, what should we do at this time?

initializer_list parameter

If the actual parameter of the function is unknown but the types of all the actual parameters are the same, you can use the formal parameter of the initializer_list type. initializer_list is a standard library type used to represent an array of values ​​of a particular type. initializer_list is defined in the header file with the same name.

Like vector, initializer_list is also a template type, and provides operations such as

1 initializer_list <T> lst; // default initialization, empty list of type T 
2 initializer_list <T> lst = {a, b, c ......};
 3 lst.size (); // number of elements 
4  lst.begin ( );
 5 lst.end ();
1 #include <iostream>
 2 #include <initializer_list>
 3  using  namespace std;
 4  void func (initializer_list < int > lst)
 5  {
 6      for (auto beg = lst.begin (); beg! = Lst.end (); ++ beg)
 7          cout << * beg << "  " ;
 8  }
 9  int main ()
 10  {
 11      func ({ 1 , 2 , 3 , 4 }); // Formal parameter transfer value sequence, you must put the sequence 12      return in curly brackets
 0;
13 }

It should be noted that the elements in the initializer_list object are constant values, and the values ​​of their elements cannot be changed.

 

Omitted parameter

Omitting the parameter is set to facilitate C ++ to access some special C code. It should be noted that objects of most class types cannot be copied correctly when passed to omitted parameter.

There are two forms:

void foo(…);//

void foo (parm_list,…); // parm_list specifies some parameter types

Guess you like

Origin www.cnblogs.com/cs0915/p/12714462.html