假设我有用C++ 98构建的监听器,它们是抽象的,例如必须实现ActionPerformed.在C++中,有一种方法可以类似于Java:
button.addActionListener(new ActionListener() {
public void actionPerfored(ActionEvent e)
{
// do something.
}
});
Run Code Online (Sandbox Code Playgroud)
谢谢
不完全是,但你可以用Lambdas做一些事情.
即:
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 )
{
...
}
));
Run Code Online (Sandbox Code Playgroud)
不,你不能那样做.
但是,如果你放弃"类似于Java",只使用一个仿函数,你会发现C++ 11 lambdas非常有用.
这是C++,而不是Java,因此编写像Java这样的C++不会很好.
无论如何,您可以创建适配器功能.假设
typedef int ActionEvent; // <-- just for testing
class ActionListener
{
public:
virtual void actionPerformed(const ActionEvent& event) = 0;
};
Run Code Online (Sandbox Code Playgroud)
然后我们可以编写一个包含函数对象的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);
}
Run Code Online (Sandbox Code Playgroud)
然后make_action_listener用来包裹一个lambda,例如(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;
}));
}
Run Code Online (Sandbox Code Playgroud)
请注意,这远不是惯用的C++,在这里addActionListener()您应该只使用const std::function<void(const ActionEvent&)>&一个模板参数,甚至模板参数以获得最大效率,并直接提供lambda.
| 归档时间: |
|
| 查看次数: |
3882 次 |
| 最近记录: |