Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does C++0x support Anonymous Inner Classes?

Tags:

c++

c++11

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

like image 966
jmasterx Avatar asked Dec 03 '22 05:12

jmasterx


2 Answers

Not exactly, but you can do something close with Lambdas.

i.e.:

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 )
   {
       ...
   }
));
like image 117
Gerald Avatar answered Dec 05 '22 19:12

Gerald


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.

like image 42
Ben Voigt Avatar answered Dec 05 '22 21:12

Ben Voigt