Ree*_*sey 25
是.在标准C++中,您可以使用va_arg和...语法.请参阅MSDN了解详细信息.
对于C++/CLI,有一个快捷方式.
你这样做:
void TheMethod( String^ firstArgument, ... array<Object^>^ variableArgs );
Run Code Online (Sandbox Code Playgroud)
如今,使用现代 C++,您可以对可变参数函数使用现代类型安全实践。
如果所有参数都具有相同类型,则使用可变参数模板或 std::initializer_list
使用可变参数模板,您可以使用递归遍历可变参数列表。可变模板示例:
template<class T>
void MyFoo(T arg)
{
DoSomething(arg);
}
template<class T, class... R>
void MyFoo(T arg, R... rest)
{
DoSomething(arg);
// If "rest" only has one argument, it will call the above function
// Otherwise, it will call this function again, with the first argument
// from "rest" becoming "arg"
MyFoo(rest...);
}
int main()
{
MyFoo(2, 5.f, 'a');
}
Run Code Online (Sandbox Code Playgroud)
这保证了如果 DoSomething 或您在递归调用 MyFoo 之前运行的任何其他代码对传递给函数 MyFoo 的每个参数的类型具有重载,则将调用该确切的重载。
使用 std::initializer_list,您可以使用一个简单的 foreach 循环来遍历参数
template<class T>
void MyFoo(std::initializer_list<T> args)
{
for(auto&& arg : args)
{
DoSomething(arg);
}
}
int main()
{
MyFoo({2, 4, 5, 8, 1, 0}); // All the arguments have to have the same type
}
Run Code Online (Sandbox Code Playgroud)