Search code examples
c++classlambdaconstexprcompile-time

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?


Solution

  • 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?