Can a lambda function be specified as constexpr

In theory, the result of a lambda function could be known at compile time, but there seems to be no way to specify this

Here's what I've tried:

#include <array>

constexpr unsigned int func1(unsigned int y)
{
        return y+3;
}

constexpr unsigned int func2(unsigned int y)
{
        return [y]() -> const unsigned int { return y+3; }() +3;
}

int main(int, char **)
{
        const unsigned long y=7;
        auto lambda=[y]() -> const unsigned int { return y+3; };

        int a0[lambda()];
        int a1[func1(7)];
        int a2[func2(7)];

        std::array<int, lambda()> b0;
        std::array<int, func1(7)> b1;
        std::array<int, func1(lambda())> b10;
        std::array<int, func2(7)> b2;
}

      

Here's what g ++ thought of my theory:

Compiling
.../gcc-4.8.1/bin/g++ -g -O0 -g3 -fno-inline -std=c++11 -Dunix -c l                ambda.cpp -o Linux/lambda.o
lambda.cpp: In function 'constexpr unsigned int func2(unsigned int)':
lambda.cpp:10:53: error: call to non-constexpr function 'func2(unsigned int)::__                lambda0'
  return [y]() -> const unsigned int { return y+3; }() +3;
                                                     ^
lambda.cpp: In function 'int main(int, char**)':
lambda.cpp:22:25: error: call to non-constexpr function 'main(int, char**)::__la                mbda1'
  std::array<int, lambda()> b0;
                         ^
lambda.cpp:22:25: error: call to non-constexpr function 'main(int, char**)::__la                mbda1'
lambda.cpp:22:26: note: in template argument for type 'long unsigned int'
  std::array<int, lambda()> b0;
                          ^
lambda.cpp:22:30: error: invalid type in declaration before ';' token
  std::array<int, lambda()> b0;
                              ^
lambda.cpp:24:31: error: call to non-constexpr function 'main(int, char**)::__la                mbda1'
  std::array<int, func1(lambda())> b10;
                               ^
lambda.cpp:24:31: error: call to non-constexpr function 'main(int, char**)::__la                mbda1'
lambda.cpp:24:33: note: in template argument for type 'long unsigned int'
  std::array<int, func1(lambda())> b10;
                                 ^
lambda.cpp:24:38: error: invalid type in declaration before ';' token
  std::array<int, func1(lambda())> b10;
                                      ^
lambda.cpp:25:25: error: 'constexpr unsigned int func2(unsigned int)' called in                 a constant expression
  std::array<int, func2(7)> b2;
                         ^
lambda.cpp:25:26: note: in template argument for type 'long unsigned int'
  std::array<int, func2(7)> b2;
                          ^
lambda.cpp:25:30: error: invalid type in declaration before ';' token
  std::array<int, func2(7)> b2;
                              ^
gmake: *** [Linux/lambda.o] Error 1

      

Can lambdas be used as const expressions?

+3


source to share





All Articles