传递嵌套函子 (C++)
有没有办法在 main 之外传递 foo_ ?我在另一个关于函子的问题中看到了一些关于 Boost 的内容。看起来可能有用。这是该问题中提到 Boost 的答案。如果可以的话,我想避免使用Boost。
#include <iostream>
int main()
{
class foo {
public:
void operator()() {
std::cout << "Hello" << std::endl;
}
};
foo foo_;
foo_();
return 0;
}
Is there a way to pass foo_ around outside of main? I saw something about Boost in another question regarding functors. That looks like it may work. Here's the answer mentioning Boost in that question. If I can, I would like to avoid Boost.
#include <iostream>
int main()
{
class foo {
public:
void operator()() {
std::cout << "Hello" << std::endl;
}
};
foo foo_;
foo_();
return 0;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
不,当前本地类型不允许进入模板(否则您可以使用 boost 或 std::tr1::function )。然而,你也许可以用 OOP 来实现,其中 Foo 继承了一些东西(它有一个你的 foo 实现的虚拟 operator() 函数),然后你将一个 ptr 传递给 Foo。
No, currently local types aren't allowed to go into templates (otherwise you could've used boost or std::tr1::function). However, you could maybe do it OOP, where Foo inherits something (that has a virtual opeator() func that your foo implemen ts) and you pass a ptr to Foo around instead.
如果这就是您的意思,则函数局部类不能用作模板参数。仅 C++0x 支持此功能。
function local classes cannot be used as template arguments if that's what you mean. This will only be supported by C++0x.
似乎可以使用本地类的静态函数的地址。但是,operator() 必须是非静态成员函数,因此您需要给它一个名称:
It appears possible to use the address of a static function of a local class. However, operator() must be a non-static member function, hence you'll need to give it a name:
我认为不可能调用当前范围内未定义的类的成员。在这种情况下,函子不保留任何状态,其行为类似于不带参数且不返回值的函数,因此您可以将其实例分配给原始函数指针。然而,它不再是一个foo:它只是一个函数指针。
一种解决方案是从全局范围内定义的纯虚拟基类派生 foo,例如:
您现在可以将 foo 的实例作为 base,虚拟 doit() 方法将按预期被调用。
I don't think it is possible to invoke a member of a class that is not defined in the current scope. The functor in this case retains no state and behaves like a function that takes no parameters and returns no value, so you could assign an instance of it to a raw function pointer. However, it is then no longer a foo: it is just a function pointer.
One solution is to derive foo from a pure virtual base class defined at global scope, such as:
You can now pass an instance of foo around as base, and the virtual doit() method will be invoked as expected.
编辑:这似乎不是有效的 C++,尽管有些编译器毫无怨言地接受它。
好吧,如果你有一些接受函子作为模板参数的东西,你可以将任何东西传递给它作为函子,尽管我不完全确定这就是你想要的?
EDIT: this does not appear to be valid C++ although some copilers take it without complaint.
well if you have something accepting functors as a template parameter, you could pass anything to it behaving as a functor, although I'm not entirely sure that is what you're after?