简体   繁体   中英

Passing relative function pointers as parameters

Say I have a namespace KeyManager and I have the function press

std::vector<std::function<void()>*> functions;

void KeyManager::addFunction(std::function<void()> *listener)
{
    functions.push_back(listener);
}

void KeyManager::callFunctions()
{
    for (int i = 0; i < functions.size(); ++i)
    {
        // Calling all functions in the vector:
        (*functions[i])();
    }
}

and I have class Car and in the constructor of car I want to pass it's relative function pointer to a class function like so:

void Car::printModel()
{
    fprintf(stdout, "%s", this->model.c_str());
}

Car::Car(std::string model)
{
    this->model = model;
    KeyManager::addFunction(this->printModel);
}

I get the following error when trying to pass the relative function pointer:

error C3867: 'Car::printModel': function call missing argument list; use '&Car::printModel' to create a pointer to member

How do I fix this?

You have to use std::bind to create an std::function that invokes a member function on a specific object. This is how that works:

Car::Car(std::string model)
{
    this->model = model;
    KeyManager::addFunction(std::bind(&Car::printModel, this));
}

Is there a specific reason why you are passing the std::function as pointer, instead of a value? If you are not binding any arguments that are expensive to copy, I would rather not do that.

Also, callFunctions can be simplified using a lambda:

void KeyManager::callFunctions() 
{
    for (auto & f : functions) 
        f();
}

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