i73 i73 -4 years ago 68
C++ Question

Passing a generic template parameter from a map?

I am coming from c# so please excuse anything I may get wrong in trying to ask this question.

I have created a map that contains a string and a method to handle invoking a method by a string:

//MyClass.h
void SerializeCustomData();
std::unordered_map<std::string, void(MyClass::*)()> functionMap;

MyMethod() {
functionMap["SerializeCustomData"] = &MyClass::SerializeCustomData;
};


My question is; how can I have my map take in a parameter for the method? Either a generic type or a string in c++?

Example:

SerializeCustomData(std::string);

Answer Source
#include <functional>
#include <iostream>
#include <unordered_map>

class MyClass
{
    std::unordered_map<std::string, std::function<void(MyClass&, std::string)>> functionMap;
public:
    void MyMethod()
    {
        functionMap.emplace("SerializeCustomData", &MyClass::SerializeCustomData);
    }

    void CallSerialize()
    {
        functionMap.at("SerializeCustomData")(*this, "argument");
    }

    void SerializeCustomData(std::string s)
    {
        std::cout << "hello: " << s << "\n";
    }
};

int main()
{
    MyClass c;
    c.MyMethod();
    c.CallSerialize();
}

Here the function from the map is called with a MyClass& argument and a string. Note that the MyClass isn't bound to the callback, and so we're passing it explicitly.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download