现代C ++实现具有可变数量的int参数的函数的最佳方法 [英] Modern C++ best way to implement a function with a variable number of int parameters
本文介绍了现代C ++实现具有可变数量的int参数的函数的最佳方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在现代C ++(即version> = 11)中,实现具有可变数量的int参数的函数的最佳方法是什么?
In modern C++(ie, version>=11), what is best way to implement a function with a variables number of int parameters?
I只需要 int
s,而不是一般类型。
I only want int
s, not a general type.
每个参数的类型都是int并且不允许其他类型。
Each of the parameters is of type int and no other type is allowed.
void foo(/*WHAT'S HERE*/) {
// and how do I access the arguments here?
}
int main()
{
foo(34,1);
foo(9,2,66,1);
// etc
return 0;
}
推荐答案
最好的办法是
template<typename T, typename ... Args>
return_type Functionname(T arg1, ...)
{ }
例如,如果您想对可变数量的参数求和,请使用类似的东西:
For example, if you want to sum a variable number of arguments, use something like:
template<typename T, typename... Args>
T adder(T first, Args... args) {
return first + adder(args...);
}
希望有帮助!
编辑:这个问题可能也有帮助。
This question might help, too.
这篇关于现代C ++实现具有可变数量的int参数的函数的最佳方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文