Search code examples
c++templatesc++20c++-concepts

How to make a function accept certain parameters using templates and concepts


I want to write a function that accepts a certain number of parameters using constant templates, for example:

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

foo<1>(0); // success
foo<2>(0); // error
foo<3>(0, 0, 0); // success

count in templates decides how many parameters it can accept.

I tried to write a prototype like this

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

template <int size>
void foo(int... args) requires equal<sizeof...(args), size>
{ ... }

and it fails to complie. What is the correct way to do it, or is there a simplier method.

thanks very much


Solution

  • int... args is not the way to have int arg0, int arg1, .., int argN

    int... is used for number0, number1, ..., numberN
    as in std::integer_sequence<int, 4, 8, 15, 16, 23, 42>

    You might do:

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

    Demo