dimanche 19 avril 2020

Store generic callback in a map

i would like create a map of id / generic callback but I don't know if it's feasible. My idea is like this: Different king od object

class Class1
{
public:
    bool run(const int &temp){
        std::cout << "worker1:" << temp << std::endl;
        return 0;
    }
};
class Class2
{
public:
    bool run(const std::string &temp){
        std::cout << "worker2:" << temp << std::endl;
        return 0;
    }
};

The template for the Callback object:

template <typename ReturnType, typename... Args>
class Callback
{
private:
    std::function<ReturnType> _function;

public:
    Callback(std::function < ReturnType(Args...)> function) 
        : _function(function){}

    auto run(Args... args)
    {
        return function(std::forward<Args>(args)...);
    }
};

an example of use

int main() {
    Class1 class1;
    Class2 class2;

    std::map<int, Callback> cbs;

    cbs[1] = std::bind(&Class1::run, &class1, std::placeholders::_1));
    cbs[2] = std::bind(&Class1::run, &class1, std::placeholders::_1));

     cbs[1].run(1);
     cbs[2].run("string msg");           
}

Aucun commentaire:

Enregistrer un commentaire