Variable number of arguments in C++?

后端 未结 17 1786
-上瘾入骨i
-上瘾入骨i 2020-11-21 23:13

How can I write a function that accepts a variable number of arguments? Is this possible, how?

相关标签:
17条回答
  • 2020-11-21 23:31

    If you know the range of number of arguments that will be provided, you can always use some function overloading, like

    f(int a)
        {int res=a; return res;}
    f(int a, int b)
        {int res=a+b; return res;}
    

    and so on...

    0 讨论(0)
  • 2020-11-21 23:32

    There is no standard C++ way to do this without resorting to C-style varargs (...).

    There are of course default arguments that sort of "look" like variable number of arguments depending on the context:

    void myfunc( int i = 0, int j = 1, int k = 2 );
    
    // other code...
    
    myfunc();
    myfunc( 2 );
    myfunc( 2, 1 );
    myfunc( 2, 1, 0 );
    

    All four function calls call myfunc with varying number of arguments. If none are given, the default arguments are used. Note however, that you can only omit trailing arguments. There is no way, for example to omit i and give only j.

    0 讨论(0)
  • 2020-11-21 23:33
    // spawn: allocate and initialize (a simple function)
    template<typename T>
    T * spawn(size_t n, ...){
      T * arr = new T[n];
      va_list ap;
      va_start(ap, n);
      for (size_t i = 0; i < n; i++)
        T[i] = va_arg(ap,T);
      return arr;
    }
    
    

    User writes:

    auto arr = spawn<float> (3, 0.1,0.2,0.3);
    

    Semantically, this looks and feels exactly like an n-argument function. Under the hood, you might unpack it one way or the other.

    0 讨论(0)
  • 2020-11-21 23:36

    in c++11 you can do:

    void foo(const std::list<std::string> & myArguments) {
       //do whatever you want, with all the convenience of lists
    }
    
    foo({"arg1","arg2"});
    

    list initializer FTW!

    0 讨论(0)
  • 2020-11-21 23:38

    The only way is through the use of C style variable arguments, as described here. Note that this is not a recommended practice, as it's not typesafe and error-prone.

    0 讨论(0)
  • 2020-11-21 23:38

    It's possible you want overloading or default parameters - define the same function with defaulted parameters:

    void doStuff( int a, double termstator = 1.0, bool useFlag = true )
    {
       // stuff
    }
    
    void doStuff( double std_termstator )
    {
       // assume the user always wants '1' for the a param
       return doStuff( 1, std_termstator );
    }
    

    This will allow you to call the method with one of four different calls:

    doStuff( 1 );
    doStuff( 2, 2.5 );
    doStuff( 1, 1.0, false );
    doStuff( 6.72 );
    

    ... or you could be looking for the v_args calling conventions from C.

    0 讨论(0)
提交回复
热议问题