【问题标题】:Modern C++ best way to implement a function with a variable number of int parameters [duplicate]现代C ++实现具有可变数量int参数的函数的最佳方法[重复]
【发布时间】:2019-11-22 01:15:29
【问题描述】:

在现代 C++(即版本>=11)中,实现具有多个 int 参数的变量的函数的最佳方法是什么?

我只想要ints,不是一般的类型。

每个参数都是 int 类型,不允许使用其他类型。

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

【问题讨论】:

  • 我在重复列表中添加了另一个问题,其中包括将参数限制为 int
  • 为什么不传入vector<int>
  • 为什么这不起作用:ideone.com/TvLalR
  • @M.M 很多,很多,...,非常感谢。以下在 C++17 中工作,非常漂亮。 template <typename... U> typename std::enable_if<(std::is_same<U, int>::value && ...), void>:: type foo(U... ints) { const int size = sizeof...(ints); int intarray[size] = {ints...}; }
  • @RFS 美女在旁观者的眼中 :)

标签: c++ c++11 c++14 c++17 variadic-templates


【解决方案1】:

最好的办法是使用可变参数函数。

template<typename T, typename ... Args>
return_type Functionname(T arg1, ...)
{ }

例如,如果您想对可变数量的参数求和,请使用类似:

template<typename T, typename... Args>
T adder(T first, Args... args) {
  return first + adder(args...);
}

希望这会有所帮助!

编辑:这个问题也可能有帮助。

Variable number of arguments in C++?

【讨论】:

  • 如何为 int 执行此操作?我只想要int。
  • 您在第一个 sn-p 中的函数参数语法没有按照您的预期进行。您正在为(C 风格)可变参数函数声明可变参数模板。 adder 示例缺少基本情况,因为 C++17 折叠表达式是形成该示例的更易读的方式。将typename 替换为int 会使参数成为非类型模板参数,并且您的最后一个代码块格式不正确,因为Args 不是类型。
  • @RFS 可变参数模板接受 any 参数的 any 类型,因此它适用于 int 参数。如果您的问题是如何将可变参数模板限制为接受int 作为参数,那么您应该在问题中澄清这一点。
  • @GokuMizuno “用 int 替换所有类型名”是不可能的
猜你喜欢
  • 1970-01-01
  • 2011-02-13
  • 2011-12-24
  • 1970-01-01
  • 2011-07-14
  • 1970-01-01
  • 1970-01-01
  • 2010-09-11
相关资源
最近更新 更多