未记录的GCC c++ 11扩展?在lambda捕获列表中捕获任意表达式
Undocumented GCC C++11 extension? Capturing arbitrary expressions in lambda capture lists
奇怪的是,GCC 4.7.2似乎对以下代码没有问题:
template<typename T>
T&& identity(T&& x1) {
return std::forward<T>(x1);
}
int main(int, char**) {
int x1 = 1;
int &x2 = identity(x1);
auto f = [&x1]() mutable {
x1 = x1 + 1;
};
auto g1 = [y=x2+1]() {
static_assert(std::is_same<decltype(y), const int>::value, "fail");
std::cout << "g1: " << y << std::endl;
};
auto h1 = [y=identity(x1)+1]() {
static_assert(std::is_same<decltype(y), const int>::value, "fail");
std::cout << "h1: " << y << std::endl;
};
auto g2 = [&y=x2]() {
static_assert(std::is_same<decltype(y), int&>::value, "fail");
std::cout << "g2: " << y << std::endl;
};
auto h2 = [&y=identity(x1)]() {
static_assert(std::is_same<decltype(y), int&>::value, "fail");
std::cout << "h2: " << y << std::endl;
};
f(); g1(); h1(); g2(); h2();
f(); g1(); h1(); g2(); h2();
return 0;
}
结果如下:
g1: 2
h1: 2
g2: 2
h2: 2
g1: 2
h1: 2
g2: 3
h2: 3
我似乎找不到任何关于在lambda捕获列表中捕获任意表达式的提及,即使在n3285(日期为2012-10-02)中也是如此。而且,我似乎找不到任何关于这个作为官方GCC扩展的文档。
这是一个未记录的GCC扩展(一个VLAs作为结构成员,一个GCC已经提前实现的提议/即将到来的c++特性,两者都没有,还是什么?
正如评论中所指出的,该特性与最近的一个提案大致相似,但它在最初的标准化之前很久就实现了。在标准开发过程中,GCC充当了一个原型,最初反映了作者喜欢的任何想法,后来对其进行了改进。一些为了保持标准的合理简单而不得不被删减的想法正以提案的形式重新引入。lambda有很大的成长空间。
现在,这只是另一个bug。它从未从最初的实现中删除,因为还没有人报告它。
更新:这是c++ 14以来的标准特性
相关文章:
- 列表.erase 中的 lambda 表达式
- Simulink "Access Violation"写入 C++ lambda 函数捕获列表中的 PWork 变量
- 将 lambda 函数转换为具有混合 lambda 引入器和参数列表的函子结构
- 没有捕获列表的 lambda 通常作为普通函数实现吗?
- C++参数列表中带有省略号的 lambda
- 将类成员指针传递给 Lambda 捕获列表 c++11
- 在为工作线程访问 lambda 中捕获的向量列表中的元素引用时,是否需要互斥锁?
- 与lambda一起使用虚拟继承在初始化列表中捕获此问题的GCC错误
- 在没有捕获列表的情况下访问 lambda 中的变量
- Do=在lambda的捕获列表中捕获this指针
- 如何使可变 lambda 捕获列表的某些成员变得非常量
- 在类中使用时,lambda 捕获列表中的 [this] 和 [&] 是否等效?
- 为什么 lambda 表达式的捕获列表无法使用结构化绑定分解
- C++ lambda 参数列表
- 构造函数初始化列表中可变参数的Lambda捕获
- C++11 lambda捕获列表[=]使用引用
- 带有变量参数列表的c++11 lambda函数
- 构造函数初始值设定项列表中的 Lambda 可以使用哪些标识符
- 是否可以提取 lambda 的捕获列表
- 您可以在类的初始化列表中使用 lambda 吗?