Karim Abdel Hamid
Karim Abdel Hamid

Reputation: 423

Map of methods from different classes in C++

I'm working on mapping keyboard input to functions. I've done significant portion of it, but now I need to bind a string to a function so that when the key referenced to that string is pressed, it will be called.

I know I can use template void BindStringToAction(std::string key, T* obj, R (T::*methodPointer)(float));

But the issue is storing it for continued use. These methods could have a base class and could all have the same input (float) and return type (void) but storing them in a map requires a set ClassName.

So essentially the question is how do i store a map of a string and method pointer, the latter of which could be in any class.

Unreal does the same thing but I can't find an implementation or similar information. I found std::function but that also relies on class names that vary and therefore I can't make a map for it.

Upvotes: 1

Views: 1617

Answers (1)

Benjamin Navarro
Benjamin Navarro

Reputation: 167

With C++11, you can use lambdas to wrap your callbacks functions/methods. For example:

struct A {
    void callback(float in) {
        std::cout << "A : " << in << std::endl;
    }
};

struct B {
    void callback(float in) {
        std::cout << "B : " << in << std::endl;
    }
};

int main() {
    A a;
    B b;
    std::map<std::string, std::function<void(float)>> callbacks;
    callbacks["A"] = [&a](float in){a.callback(in);};
    callbacks["B"] = [&b](float in){b.callback(in);};

    callbacks["A"](3.14);
    callbacks["B"](42.);
}

The output is:

A : 3.14
B : 42

This way it doesn't matter if your callback is a function, a method or a lambda. I use this system for something similar to what you are doing and it works just fine.

Upvotes: 2

Related Questions