小编joe*_*ius的帖子

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

在 python 中,我可以使用*args允许可变数量的输入到函数中。例如,以下代码段将打印出调用 f 时传递的所有参数:

def f(*args):
  for a in args:
    print(a)
Run Code Online (Sandbox Code Playgroud)

我希望能够在具有以下要求的 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
};
Run Code Online (Sandbox Code Playgroud)

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

c++ templates variadic-functions c++11

2
推荐指数
1
解决办法
51
查看次数

标签 统计

c++ ×1

c++11 ×1

templates ×1

variadic-functions ×1