Variable number of parameters in function in C++

前端 未结 8 1860
借酒劲吻你
借酒劲吻你 2020-12-07 20:32

How I can have variable number of parameters in my function in C++.

Analog in C#:

public void Foo(params int[] a) {
    for (int i = 0; i < a.Leng         


        
8条回答
  •  既然无缘
    2020-12-07 21:20

    The real C++ solution is variadic templates. You'll need a fairly recent compiler and enable C++11 support if needed.

    Two ways to handle the "do the same thing with all function arguments" problem: recursively, and with an ugly (but very very Standards compliant) solution.

    The recursive solution looks somewhat like this:

    template
    void print(ArgTypes... args);
    template
    void print(T t, ArgTypes... args)
    {
      std::cout << t;
      print(args...);
    }
    template<> void print() {} // end recursion
    

    It generates one symbol for each collection of arguments, and then one for each step into the recursion. This is suboptimal to say the least, so the awesome C++ people here at SO thought of a great trick abusing the side effect of a list initialization:

    struct expand_type {
      template
      expand_type(T&&...) {}
    };
    template
    void print(ArgTypes... args)
    { 
      expand_type{ 0, (std::cout << args, 0)... };
    }
    

    Code isn't generated for a million slightly different template instantiations, and as a bonus, you get preserved order of you function arguments. See the other answer for the nitty gritty details of this solution.

提交回复
热议问题