如何使用模板和概念使函数接受某些参数

yua*_*liu 5 c++ templates c++-concepts c++20

我想编写一个使用常量模板接受一定数量参数的函数,例如:

template<int count>
void foo(int... args) { ... }

foo<1>(0); // success
foo<2>(0); // error
foo<3>(0, 0, 0); // success
Run Code Online (Sandbox Code Playgroud)

count在模板中决定它可以接受多少个参数。

我尝试写一个这样的原型

template <int a, int b>
concept equal = (a == b);

template <int size>
void foo(int... args) requires equal<sizeof...(args), size>
{ ... }
Run Code Online (Sandbox Code Playgroud)

它没有遵守。正确的方法是什么,或者有更简单的方法。

非常感谢

Jar*_*d42 5

int... args不是拥有的方法int arg0, int arg1, .., int argN

int...用于number0, number1, ..., numberN
std::integer_sequence<int, 4, 8, 15, 16, 23, 42>

你可能会这样做:

template<int count, std::same_as<int> ...Ints>
void foo(Ints... args) requires (sizeof...(args) == count)
{
  // ...
}
Run Code Online (Sandbox Code Playgroud)

演示