在 python 中,我可以使用 *args
允许向函数输入可变数量的输入。例如,以下代码片段将打印出调用 f 时传递的所有参数:
def f(*args):
for a in args:
print(a)
我希望能够在 C++11 中实现这样的模式,并满足以下要求:
函数 f 将始终接受某种类型 T 的值,然后接受可变数量的输入;这可能包括 0 个额外输入。
附加输入不一定是同一类型,因此使用初始值设定项列表不起作用。
函数 f 将被另一个函数 g 调用,该函数需要将可选参数转发给 f:
T g(const T& x, args...) {
T output = f(x, args...);
return output;
};
T f(const T& x, args...) {
// do some stuff and return an object of type T
};
如何解决这个设计问题?我已经尝试过可变参数模板,但似乎无法使我的实现正常工作(可以编译,但由于右值引用问题而无法链接)。
最佳答案
以下是用 C++ 编写此代码的方法:
template <class... A>
T f(const T &x, A &&... arg)
{
// do some stuff and return an object of type T
}
template <class... A>
T g(const T &x, A &&... arg)
{
T output = f(x, std::forward<A>(arg)...);
return output;
}
注意,由于涉及到模板,所以代码必须是in a header file以防止链接问题。
关于c++ - 如何实现可变参数模式以将可变数量的参数转发给 C++11 中的函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56740835/