Ste*_*Lin 13 c++ lambda gcc c++11
奇怪的是,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;
}
Run Code Online (Sandbox Code Playgroud)
结果如下:
g1: 2
h1: 2
g2: 2
h2: 2
g1: 2
h1: 2
g2: 3
h2: 3
Run Code Online (Sandbox Code Playgroud)
我似乎找不到在lambda捕获列表中捕获任意表达式的任何提及,即使在n3285(日期为2012-10-02).此外,我似乎无法在任何地方找到任何关于此的官方GCC扩展的文档.
这是一个无证件的GCC扩展(作为结构成员的一个VLAs,一个提议的/即将推出的C++特性,GCC已经提前实施,既不是,也不是,或者是什么?
正如评论中所指出的,该功能与最近的提案大体相似,但它在最初的标准化之前就已实施.GCC在标准开发期间作为原型,最初反映了作者喜欢的任何想法,后来经过改进.为了使标准保持相当简单,必须进行修整的一些想法将被重新引入作为提案.Lambdas有很大的发展空间.
现在,这只是另一个错误.它从未从原始实现中删除,因为还没有人报告它.
更新:这是自C++ 14以来的标准功能.