type function(type arg1, ...) { }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
| #include <iostream> #include <cstdarg> using namespace std;
int vsum(int count, ...) {
va_list ap;
va_start(ap, count);
int val(0); int sum(0);
for (int i=0; i<count; ++i) { val = va_arg(ap, int); sum += val; }
va_end(ap);
return sum; }
int main() { cout << vsum(4, 1,2,3,4) << endl; }
|
示例:递归求和
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| #include <iostream> using namespace std;
template <typename T> T vsum(const T &t) { return t; }
template <typename T, typename ... Args> T vsum(const T &t, const Args&... args) { T sum(0); sum += t; sum += vsum(args...); return sum; }
int main() { cout << vsum(1,2,3,4) << endl; }
|
参考:https://blog.csdn.net/elloop/article/details/50092631