假设我有用C++ 98构建的侦听器,它们是抽象的,并且必须例如实现ActionPerformed。在C++ 0x中是有办法做到这类似于Java:C++ 0x是否支持匿名内部类?
button.addActionListener(new ActionListener() {
public void actionPerfored(ActionEvent e)
{
// do something.
}
});
感谢
假设我有用C++ 98构建的侦听器,它们是抽象的,并且必须例如实现ActionPerformed。在C++ 0x中是有办法做到这类似于Java:C++ 0x是否支持匿名内部类?
button.addActionListener(new ActionListener() {
public void actionPerfored(ActionEvent e)
{
// do something.
}
});
感谢
不完全是,但你可以做一些与兰姆达斯关系密切。
即:
class ActionListener
{
public:
typedef std::function<void(ActionEvent&)> ActionCallback;
public:
ActionListener(ActionCallback cb)
:_callback(cb)
{}
void fire(ActionEvent& e)
{
_callback(e);
}
private:
ActionCallback _callback;
};
..
button.addActionListener(new ActionListener(
[](ActionEvent& e)
{
...
}
));
这是C++,而不是Java,因此像Java一样编写C++将无法正常工作。
无论如何,你可以创建一个适配器功能。假设
typedef int ActionEvent; // <-- just for testing
class ActionListener
{
public:
virtual void actionPerformed(const ActionEvent& event) = 0;
};
然后,我们可以写的ActionListener的模板子类,包装了一个函数对象:
#include <memory>
template <typename F>
class ActionListenerFunctor final : public ActionListener
{
public:
template <typename T>
ActionListenerFunctor(T&& function)
: _function(std::forward<T>(function)) {}
virtual void actionPerformed(const ActionEvent& event)
{
_function(event);
}
private:
F _function;
};
template <typename F>
std::unique_ptr<ActionListenerFunctor<F>> make_action_listener(F&& function)
{
auto ptr = new ActionListenerFunctor<F>(std::forward<F>(function));
return std::unique_ptr<ActionListenerFunctor<F>>(ptr);
}
,然后用make_action_listener
包拉姆达e.g(http://ideone.com/SQaLz)。
#include <iostream>
void addActionListener(std::shared_ptr<ActionListener> listener)
{
ActionEvent e = 12;
listener->actionPerformed(e);
}
int main()
{
addActionListener(make_action_listener([](const ActionEvent& event)
{
std::cout << event << std::endl;
}));
}
注意,这绝不是地道的C++,在addActionListener()
,你应该简单地采取const std::function<void(const ActionEvent&)>&
,甚至获得最高效率的模板参数,并直接提供拉姆达。
我认为,我们可以在C做++使用lambda表达式
button.addActionListener([]()->ActionListener*{ struct A: ActionListener {
void actionPerfored(ActionEvent e)
{
// do something.
}
}; return new A;}());
它应该很容易在宏来包装这件事。
太糟糕了,我们不能'''{return new struct:ActionListener {...}; }'。这实际上看起来很像Java版本... – Xeo 2012-01-23 01:08:24
一个合适的C++接口当然会有任何这样的“addActionListener”带一个* proper * functor,一个重载'operator()',而不是覆盖一个虚函数并依赖于继承。 – 2011-12-23 18:15:04