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

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?


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).