这个问题可能只对了解支持闭包的编程语言的人有意义。如果您不这样做,请不要评论“您为什么要这样做?”:这样做有很多正当理由。
在函数式语言中,定义捕获已经定义的局部变量的局部函数是很常见的。在 C++ 中,这看起来像(但当然是非法的):
#include <iostream>
using namespace std;
int main()
{
int x = 0;
int f() { return x + 1; }
cout << f() << endl; // would print 1
x = 2;
cout << f() << endl; // would print 3
}
为了实现这一点,C++11 引入了lambda 函数,因此实际上可以以一种相当不错的方式来实现它(虽然,不像函数式语言中那样好 ;-)):
#include <iostream>
using namespace std;
int main()
{
int x = 0;
auto f = [&] () { return x + 1; };
cout << f() << endl; // actually compiles and prints 1
x = 2;
cout << f() << endl; // actually compiles and prints 3
}
我的问题是:现在可以通过引用来自动捕获函数的自由变量,对于本地定义的结构来说这不是很好吗?理想情况下,我希望能够写:
int main()
{
int x = 0;
struct A
{
int y;
A(int y) : y(y) {}
int f() { return x + y; };
};
A a1(1);
A a2(2);
cout << a1.f() << endl; // would print 1
cout << a2.f() << endl; // would print 2
x = 2;
cout << a1.f() << endl; // would print 3
cout << a2.f() << endl; // would print 4
}
我发现的唯一解决方法是将所有非本地(自由)变量作为参数手动传递给构造函数,当它们很多时,这有点痛苦:
#include <iostream>
using namespace std;
int main()
{
int x = 0;
struct A
{
// meaningful members
int y;
int f() { return x + y; };
// free variables
int & x;
// Constructor
A(
// meaningful arguments
int y,
// capturing free variables
int & x
) : y(y), x(x) {}
};
A a1(1, x);
A a2(2, x);
cout << a1.f() << endl; // prints 1
cout << a2.f() << endl; // prints 2
x = 2;
cout << a1.f() << endl; // prints 3
cout << a2.f() << endl; // prints 4
}
您是否知道任何其他解决方法可以避免手动将所有自由变量作为参数传递,或者您是否知道这些“环境感知”本地定义的结构是否被考虑用于 C++ 的未来扩展?(即,C++1y?)