dimanche 4 juin 2017

Passing multiple types to std::function C++

I am currently working on a little library and ran into a error. What I am basically trying to do is have syntax like so:

Client client("", true);

client.on("ready", [](User object) {
    object.test();
});

client.run();

and when I call _eventManager->emit("ready", new User()) The client.on(); method is suppose to fire with the given object I pass in. The object that I pass can be a variety of classes.

The way I design it so that I use a base class called "Object" and all the classes that I want to pass onto emit would be derived from Object. However I get an error when trying to do this:

error C2664: 'void Discord::Client::on(const std::string &,const std::function<void (Discord::Object)> &)': cannot convert argument 2 from 'main::<lambda_54cb69ba8322d42f33e22a0f4f4926a4>' to 'const std::function<void (Discord::Object)> &' 2> z:\projects\visual studio 2015\discord\test\source\example1.cpp(12): note: Reason: cannot convert from 'main::<lambda_54cb69ba8322d42f33e22a0f4f4926a4>' to 'const std::function<void (Discord::Object)>' 2> z:\projects\visual studio 2015\discord\test\source\example1.cpp(12): note: No user-defined-conversion operator available that can perform this conversion, or the operator cannot be called

I am clueless on what I did wrong. Code:

struct Event {
    std::string name;
    std::function<void(Object object)> function;
};

void Client::on(const std::string& name, const std::function<void(Object object)>& function) {
    _eventManager->add(name, function);
}

void Client::run() {
    User object;

    _eventManager->emit("ready", object);
}

void EventManager::add(const std::string& name, const std::function<void(Object object)>& function) {
    Event event;
    event.name = name;
    event.function = function;

    _events.push_back(event);
}

void EventManager::emit(const std::string& name, const Object& object) {
    for (unsigned int i = 0; i < _events.size(); i++) {
        Event& event = _events[i];

        if (event.name == name) {
            event.function(object);
        }
    }
}

Error Thank you in advance.

Aucun commentaire:

Enregistrer un commentaire