Domanda

I would like to know if it is possible to do Java style implementation of listener / abstract classes within a function.

In Java if I have an interface as follows:

public interface ExampleListener {
    public void callExampleListenerMethod();
}

I know can implement this interface within a method for some quick usage something like this:

someRandomJavaFunction{
   //do some stuff
   ExampleListener object = new ExampleListener() {
        @Override
        public void callExampleListenerMethod() {
            //do other stuff
        }
   });
}

Now is it possible to do the second Part somehow in C++ if I have an abstract class defined like this

class ExampleListener {

  public:
     virtual ~ExampleListener(); //virtual destructor is apparently important

     virtual void callExampleListenerMethod() = 0; //method to implement

};

Of course I can just simply use this as a Base class and I'm forced to implement the method. But is it possible to do a similar "on the fly" implementation to java?

È stato utile?

Soluzione

No, there is no equivalent of "on-the-fly" method implementation in C++. The closest thing you could do in C++ is a local class

void f()
{ 
    class MyLocalClass: public Listener
    {
        virtual void MyMethodOverride()
        {
             //... 
        }
    }

    Listener* pListener = new MyLocalClass;
    //...
}

Altri suggerimenti

In general, Armen's suggestion of a local class is usually good. For the very simple needs of your question, you could also create a derived class that captures the required implementation as a constructor argument, but this is more a curiosity than a recommendation....

struct EL : ExampleListener
{
    EL(std::function<void(void)> t) : t_(t) { }
    void callExampleListenerMethod() override { t_(); }
  private:
    std::function<void(void)> t_;
};

ExampleListener* p =
    new EL(
       []() { std::cout << "hello!\n";}
    );

p->callExampleListenerMethod();
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top