13
奇怪的是,GCC 4.7.2似乎与下面的代码没有问题:未公开的GCC C++ 11扩展?拉姆达捕捉捕捉任意表达式列出
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 as structure members,拟议/即将到来的C++功能,可GCC已经先行一步,早落实,两者都不是,这两个,还是什么?
对于这样的事情,有一个[提案](http://www.open-std.org/JTC1/SC22/WG21/docs/papers/2013/n3610.html)。 –
@JohnSchug哦,但这是注册日期2013-03-15!所以答案是“两个”? (因为这似乎早于该提议?) –
(它似乎也没有提到GCC实现,所以它可能完全独立于此开发。) –