如何实现可变参数模式以将可变数量的参数转发给C ++ 11中的函数?

时间:2019-06-24 16:44:10

标签: c++ c++11 templates variadic-functions

在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
};

如何解决此设计问题?我尝试了可变参数模板,但似乎无法使我的实现正常工作(由于右值引用问题,编译后无法链接)。

1 个答案:

答案 0 :(得分:4)

这是用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,以防止链接问题。