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

C++ requires the Template variadic number to less than N, but failed

I wanted to constrain the number of the template type to be less than 3. I expected F(1,2,3) to not compile but it actually did and printed 3.

template <typename ...Ts>
concept LessThan3 = requires {
  sizeof...(Ts) < 3;
};

template <typename... Ts>
requires LessThan3<Ts...>
void F(Ts... ts) {
  cout << sizeof...(ts);
};

int main() {
  F(1, 2, 3);  // Compile
}

However, if I explicitly put the sizeof...(Ts) < 3 in the function declaration, F(1,2,3) won’t compile, work as expected.

template <typename... Ts>
requires(sizeof...(Ts) < 3) void F(Ts... ts) {
void F(Ts... ts) {
  cout << sizeof...(ts);
};
// F(1,2,3) doesn't compile, expected.

What’s the correct way of require a concept?

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

>Solution :

sizeof...(Ts) < 3 itself does nothing, the computed result is ignored. It should be

template <typename ...Ts>
concept LessThan3 = requires {
  requires sizeof...(Ts) < 3;
};

Similar: N < 3 vs. static_assert(N < 3).

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