Variable number of parameters in function in C++

前端 未结 8 1834
借酒劲吻你
借酒劲吻你 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:22

    If you don't care about portability, you could port this C99 code to C++ using gcc's statement expressions:

    #include <cstdio>
    
    int _sum(size_t count, int values[])
    {
        int s = 0;
        while(count--) s += values[count];
        return s;
    }
    
    #define sum(...) ({ \
        int _sum_args[] = { __VA_ARGS__ }; \
        _sum(sizeof _sum_args / sizeof *_sum_args, _sum_args); \
    })
    
    int main(void)
    {
        std::printf("%i", sum(1, 2, 3));
    }
    

    You could do something similar with C++0x' lambda expressions, but the gcc version I'm using (4.4.0) doesn't support them.

    0 讨论(0)
  • 2020-12-07 21:28

    These are called Variadic functions. Wikipedia lists example code for C++.

    To portably implement variadic functions in the C programming language, the standard stdarg.h header file should be used. The older varargs.h header has been deprecated in favor of stdarg.h. In C++, the header file cstdarg should be used.

    To create a variadic function, an ellipsis (...) must be placed at the end of a parameter list. Inside the body of the function, a variable of type va_list must be defined. Then the macros va_start(va_list, last fixed param), va_arg(va_list, cast type), va_end(va_list) can be used. For example:

    #include <stdarg.h>
    
    double average(int count, ...)
    {
        va_list ap;
        int j;
        double tot = 0;
        va_start(ap, count); //Requires the last fixed parameter (to get the address)
        for(j=0; j<count; j++)
            tot+=va_arg(ap, double); //Requires the type to cast to. Increments ap to the next argument.
        va_end(ap);
        return tot/count;
    }
    
    0 讨论(0)
提交回复
热议问题