Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing this pointer and arguments of class method to local lambda function at compile time

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?

like image 396
apopa Avatar asked Dec 17 '25 14:12

apopa


1 Answers

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?

like image 190
Adrian Mole Avatar answered Dec 20 '25 06:12

Adrian Mole



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!