c++lambdac++20requires-clause

How can I use a lambda expression as constant primary expression in a requires clause?


I'm trying to understand different ways of specifying a C++ requires clause. I need some deeper understanding, not a technical solution for specifying a constraint.

Think of a template function:

template<typename T>
T func(T t) {
  return t;
}

A simple though useless requires clause could be added:

template<typename T>
requires true
T func(T t) {
  return t;
}

and I could call this function like so:

foo(1);

As far as I understand https://en.cppreference.com/w/cpp/language/constraints#Requires_clauses I could also use a constant lambda expression as a lambda expression is also a primary expression (https://en.cppreference.com/w/cpp/language/expressions#Primary_expressions).

template<typename T>
requires [] { return  true; }
T func(T t) {
  return t;
}

Using cl.exe from VS2019 / VS2022 I get a compile error similar to (translated):

error C7607: The atomic constraint has to be a constant expression of type Bool...

I tried using constexpr without any success.

What I do not want: requires ([] { return true; }())


Solution

  • A lambda expression's type is a class type determined by the compiler. It doesn't matter what the lambda returns unless you actually invoke the lambda.

    Class types are not boolean types. Since the standard requires that the expression in a requires clause be a constant expression of boolean type. You can make the lambda expression a constant expression, but you can't make it of boolean type.