简体   繁体   中英

Calling functions implicitly from derived classes

In my main.cpp I have something similar to the following:

void OnEventStart(int id)
{
    // Do some stuff
}

This function is a callback, it is only triggered (by the main sdk that this is from) when an event has occured.

I now have this class:

class SomeClass {
public:
    void OnEventStart(int id);
};

void SomeClass::OnEventStart(int id)
{
    // Do some other stuff
}

Now I want to trigger void SomeClass::OnEventStart(int id) without doing something like this:

SomeClass class;
void OnEventStart(int id)
{
     // Do some stuff

     class.OnEventStart(id);

     // AnotherClass.OnEventStart(id);
     // Another.OnEventStart(id);
}

As you can imagine, using a method like this can easily clutter up the inital function/callback.

Your question is not very clear, but I'll assume the following:

  • You have some sort of callback handler that takes a void(*)(int) .

In that case, if SomeClass is stateless, you can simply use a lambda wrapper:

my_framework_callback([]{ SomeClass{}.OnEventStart(id); });

If I misunderstood what you were asking, here's a different assumption:

  • SomeClass and similar types are stateless .

  • You're annoyed by having to instantiate SomeClass just to call one of its methods.

If that's the case, you can create a temporary instance of SomeClass on the spot:

void OnEventStart(int id)
{
     SomeClass{}.OnEventStart(id);
     AnotherClass{}.OnEventStart(id);
     Another{}.OnEventStart(id);
}

If your question is instead...

"I have various classes with the same interface, and I want to call a function on all of them."

...then one possible solution would be using an abstract base class that provides .OnEventStart() = 0 and store an std::vector of pointers to that base class.

std::vector<std::unique_ptr<MyAbstractClass>> handlers;
void OnEventStart(int id)
{
    for(auto& h : handlers)
        h->OnEventStart(id);
}

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM