struct Test
{
static const int value = []() -> int { return 0; } ();
};
使用 gcc-4.6 我得到类似错误:函数需要是 constexpr
.我尝试了将 constexpr
放在不同地方的多种组合,但没有运气.
With gcc-4.6 I get something like, error: function needs to be constexpr
. I have tried multiple combinations of putting constexpr
at various places, but no luck.
constexpr
是否也支持 lambda 函数(无论是否指定了 return
类型)?什么是正确的语法?
Is constexpr
supported for lambda functions as well (irrespective of return
type specified or not) ? What is the correct syntax ?
任何可能的解决方法?
更新:从 C++17 开始,常量表达式中允许使用 lambda.
Update: As of C++17, lambdas are permitted in constant expressions.
根据 [expr.const]/(2.6) 目前 (C++14) 不允许在常量表达式中使用 Lambda,但它们将一次 N4487被接受(可以在N4582工作草案中找到):
Lambdas are currently (C++14) not allowed in constant expressions as per [expr.const]/(2.6), but they will once N4487 is accepted (which can be found in the working draft N4582):
这个提议建议在常量中允许 lambda 表达式表达式,删除现有的限制.作者提出某些 lambda 表达式和某些闭包上的操作允许对象出现在常量表达式中.在这样做,我们还建议将闭包类型视为文字类型,如果它的每个数据成员的类型都是文字类型;并且,如果constexpr
说明符在 lambda 声明符中被省略,即生成的函数调用运算符是 constexpr
如果它满足constexpr
函数的要求(类似于constexpr
对于隐式定义已经发生的推断构造函数和赋值运算符函数).
This proposal suggests allowing lambda-expressions in constant expressions, removing an existing restriction. The authors propose that certain lambda-expressions and operations on certain closure objects be allowed to appear within constant expressions. In doing so, we also propose that a closure type be considered a literal type if the type of each of its data-members is a literal type; and, that if the
constexpr
specifier is omitted within the lambda-declarator, that the generated function call operator beconstexpr
if it would satisfy the requirements of aconstexpr
function (similar to theconstexpr
inference that already occurs for implicitly defined constructors and the assignment operator functions).
这篇关于lambda 函数/表达式是否支持 constexpr?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!