我可以在C ++中创建匿名类并捕获外部变量,如在Java? [英] Can I create anonymous classes in C++ and capture the outside variables like in Java?
问题描述
在Java中,当我需要一个回调函数时,我必须实现一个匿名类。在匿名类中,如果 final
,我可以访问外部变量。
In Java, when I need a callback function, I have to implement an anonymous class. Inside the anonymous class, I can access the outside variables if they're final
.
在C ++中的同样的事情。我理解,C ++ lambda的工作更好,但有时我需要传递在许多函数中与匿名类,我只需要传递一个实例。
Now I'm doing the same thing in C++. I understand that C++ lambda works better but sometimes I need to pass in many functions where with anonymous classes, I only need to pass in one instance.
我试过下面的例子。它与GCC 4.3.4一起工作。
I tried the following example. It works with GCC 4.3.4.
class IA {
public:
virtual int f(int x) = 0;
};
int main() {
class : public IA {
int f(int x) { return x + 1; }
} a;
doFancyWork(&a);
return 0;
}
是否可以捕获这样的外部变量?
Is it possible to capture the outside variables like this?
int main() {
int y = 100; // mark y as final if possible
class : public IA {
int f(int x) { return x + y; }
} a;
return 0;
}
UPDATE:
第二个例子将不编译。错误在这里,
The second example won't compile. The errors are here,
prog.cpp: In member function ‘virtual int main()::<anonymous class>::f(int)’:
prog.cpp:9: error: use of ‘auto’ variable from containing function
prog.cpp:7: error: ‘int y’ declared here
prog.cpp: In function ‘int main()’:
prog.cpp:7: warning: unused variable ‘y’
更新:
我刚刚意识到了更多的问题:
I just realized a few more problems in doing this:
- 我无法写入构造函数,因为类没有名称
- 初始值设置列表不允许继承。
我认为我不得不改变匿名类。
I think I have to move away from anonymous classes.
推荐答案
没有办法自动捕获这些变量,但可以使用替代方法。这是如果你想捕获通过引用:
There is no way to automatically capture those variables, but you can use an alternative approach. This is if you want to capture by reference:
int main() {
int y = 100; // mark y as final if possible
class IB : public IA {
public:
IB(int& y) : _y(y) {}
int f(int x) { return x + _y; }
private:
int& _y;
} a (y);
return 0;
}
如果要按值捕捉,只需更改
If you want to capture by value, just change int&
into int
.
无论如何,你可以考虑使用
Anyway, you may consider using a tuple of lambdas as a "multi-callback" object if that is what bothers you about individual lambdas. You would still have everything packed in one object and capturing would be done for free.
只是作为一个例子:
auto callbacks = make_tuple(
[] (int x) { cout << x << endl; },
[&] () { cout << y << endl; }, // y is captured by reference
[=] (int x) { cout << x + y << endl; }, // y is captured by value
// other lambdas here, if you want...
);
这篇关于我可以在C ++中创建匿名类并捕获外部变量,如在Java?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!