这个问题可能只对了解支持闭包的编程语言知识的人有意义。如果您不这样做,请不要评论“您为什么要这样做?”:这样做有很多合理的理由。
在函数式语言中定义局部函数来捕获已经定义的局部变量是很常见的。在 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++ 的 future 扩展? (即 C++1y?)
最佳答案
你要求的东西不可用,但你可以通过将函数与 lambda 和绑定(bind)器组合来获得类似的结果:
auto lambda = [](int i) { return x+i; };
auto a1 = std::bind(lambda,1);
auto a2 = std::bind(lambda,2);
根据更改的数量和形状,您可以颠倒解决方案并拥有一个结构,该结构将 lambda 与捕获一起使用,然后添加它自己的逻辑。
关于c++ - 在本地定义的结构中模拟非本地(或自由)变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19869074/