Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

You might do

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

Demo

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading