C++ constexpr Lambdas

Introduction

Lambdas can be a constant expression, meaning they can be evaluated during compile-time:

int main() 
{ 
    constexpr auto mylambda = [](int x, int y) { return x + y; }; 
    static_assert(mylambda(10, 20) == 30, "The lambda condition is not true."); 
} 

An equivalent example where we put the constexpr specifier in the lambda itself, would be:

int main() 
{ 
    auto mylambda = [](int x, int y) constexpr { return x + y; }; 
    static_assert(mylambda(10, 20) == 30, "The lambda condition is not true."); 
} 

This was not the case in earlier C++ standards.




PreviousNext

Related