Is constexpr supported with lambda functions / expressions?(lambda 函数/表达式是否支持 constexpr?)
问题描述
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
constexprspecifier is omitted within the lambda-declarator, that the generated function call operator beconstexprif it would satisfy the requirements of aconstexprfunction (similar to theconstexprinference that already occurs for implicitly defined constructors and the assignment operator functions).
这篇关于lambda 函数/表达式是否支持 constexpr?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:lambda 函数/表达式是否支持 constexpr?
基础教程推荐
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- CString 到 char* 2021-01-01
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- 初始化列表*参数*评估顺序 2021-01-01
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
