Variable number of arguments in C++?

后端 未结 17 1800
-上瘾入骨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: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.

提交回复
热议问题