簡體   English   中英

將相對函數指針作為參數傳遞

[英]Passing relative function pointers as parameters

說我有一個命名空間KeyManager並且我有功能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])();
    }
}

我有Car類,在car的構造函數中,我想將其相對函數指針傳遞給類函數,如下所示:

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

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

嘗試傳遞相對函數指針時出現以下錯誤:

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

我該如何解決?

您必須使用std::bind創建一個std::function來調用特定對象上的成員函數。 這是這樣的:

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

為什么將std::function作為指針而不是值傳遞給特定原因? 如果您不綁定任何復制成本很高的參數,我寧願不這樣做。

另外,可以使用lambda簡化callFunctions

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM