Say I have listeners built in C++98, they are abstract and must for example implement ActionPerformed. In C++0x is there a way to do similar to Java:
button.addActionListener(new ActionListener() {
public void actionPerfored(ActionEvent e)
{
// do something.
}
});
Thanks
Not exactly, but you can do something close with Lambdas.
ie:
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 )
{
...
}
));
No you can't do that.
If you give up on "similar to Java", though, and just use a functor, you'll find C++11 lambdas very helpful.
This is C++, not Java, so writing C++ like Java won't work well.
Anyway, you could create an adaptor function. Suppose
typedef int ActionEvent; // <-- just for testing
class ActionListener
{
public:
virtual void actionPerformed(const ActionEvent& event) = 0;
};
Then we could write a templated subclass of ActionListener that wraps a function object:
#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);
}
and then use make_action_listener
to wrap a lambda, eg ( 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;
}));
}
Note that this is far from idiomatic C++, where in addActionListener()
you should simply take a const std::function<void(const ActionEvent&)>&
, or even a template parameter for maximum efficiency, and supply the lambda directly.
I think we can do this in C++ using lambdas
button.addActionListener([]()->ActionListener*{ struct A: ActionListener {
void actionPerfored(ActionEvent e)
{
// do something.
}
}; return new A;}());
It should be easy to wrap this up in a macro.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.