理论上,lambda函数结果可以在编译时知道,但似乎没有办法指定这个
以下是我的尝试:
#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;
}
以下是g ++对我的理论的看法:
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
有没有说使用lambdas作为const表达式?