Suppose you have a scenario when you want to create a constexpr lambda inside a method for calculating something at compile time.
struct A {
int a;
constexpr A(int a) : a(a) {}
constexpr auto operator+(const A& rhs) {
constexpr auto l = [&]() {
return A(this->a + rhs.a);
};
return l();
}
};
This code doesn't compile because compiler said that this and rhs are not constant expressions. Is there a way for passing this and rhs to a local constexpr lambda?
You can't capture the a members of this and rhs (by reference) and maintain constexpr validity1; however, you can pass those members as by (const) reference arguments to your lambda:
struct A {
int a;
constexpr A(int a) : a(a) { }
constexpr auto operator+(const A rhs) {
constexpr auto l = [](const int& ta, const int& ra) {
return A(ta + ra);
};
return l(a, rhs.a); // Or return l(this->a, rhs.a) if you prefer
}
};
1 Or maybe you can, but it's messy: Lambda capture as const reference?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With