Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Using operators on a custom type in a lambda at compile time in C++

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading