I have a class which I’d like to perform operations on at compile time. In the example below I have a simple struct IntWrapper with an overloaded operator+. Using this class in any normal context seems to work fine, but it fails when used inside a lambda, why?
struct IntWrapper
{
consteval IntWrapper operator+(const IntWrapper& other) const
{
return { x + other.x };
}
int x;
};
int main()
{
// Adding normally works just fine
constexpr IntWrapper c1 = IntWrapper{ 1 } + IntWrapper{ 1 };
auto adder = [](IntWrapper x) { return x + x; };
// Using a lambda to add doesn't work
constexpr IntWrapper c2 = adder(IntWrapper{ 1 });
}
How can I get this object to work, at compile time, inside the context of a lambda?
>Solution :
Using the old C++20 rules, x + x being x.operator+(x) must be a constant expression, since it calls a consteval function but is not inside a consteval function itself. It can’t be a constant expression since it uses the function argument’s values.
Make it be inside a consteval function:
auto adder = [](IntWrapper x) consteval { return x + x; };
This is fixed with P2564R3 so a compiler following the new rules (like clang 17) will compile this, even in C++20 mode.