将 std::function 添加到向量 c++

Bha*_*waj 3 pointers function vector c++11

我有一个包含函数指针的向量

typedef bool (*fPtr)();
vector<fPtr> AlgoDB;
Run Code Online (Sandbox Code Playgroud)

我推入向量的函数定义如下

bool SAlgos1::Algo1() {
    cout << "Executing Algo1" << endl;
    return true;
} 
Run Code Online (Sandbox Code Playgroud)

以下语句用于将函数/指针添加到向量

this->AlgoDB.push_back((fPtr) &this->Algo1);
Run Code Online (Sandbox Code Playgroud)

这是传统的 C 风格函数指针用法,我正在尝试使用std::function,其中向量和函数现在修改如下

typedef function<bool()> ffptr;
vector <ffptr> fAlgoDB;

function<bool()> SAlgos1::fAlgo1(){

    cout << "Executing FAlgo1";
    return true;
}
Run Code Online (Sandbox Code Playgroud)

但是现在每当我使用这样的语句时

this->fAlgoDB.push_back(fAlgo1);this->fAlgoDB.push_back(&fAlgo1); (类型转换也无济于事 - this->fAlgoDB.push_back((ffptr) this->fAlgo1);

我收到一个错误说明

error: taking address of temporary [-fpermissive]

error: could not convert 'true' from 'bool' to 'std::function<bool()>' (即使我并没有真正调用该函数)对于每个备用编译。

如何在向量中存储函数或函数指针?编译器试图传达什么?

psc*_*ill 5

您的示例中有两个问题。

  1. 您将函数的返回类型从bool更改为function<bool>。只需将其保留为bool,因为这是您想要的返回类型。
  2. 指向成员函数指针的类型不同于指向函数的指针(参见https://isocpp.org/wiki/faq/pointers-to-members#fnptr-vs-memfnptr-types)。这是因为成员函数总是将this指针作为参数传递。您需要绑定该参数(使用std::bind,请参阅/sf/answers/530780351/)。

下面的例子编译得很好。

#include <functional>
#include <vector>
#include <iostream>

using namespace std;

class SAlgos1
{
    typedef function<bool()> ffptr;

    bool fAlgo1()
    {
        cout << "Executing FAlgo1";
        return true;
    }

    void fillAlgoDB()
    {
        fAlgoDB.push_back(bind(&SAlgos1::fAlgo1, this));
    }

    vector<ffptr> fAlgoDB;
};
Run Code Online (Sandbox Code Playgroud)

  • 我会使用 lambda 而不是 `bind`。当我们没有 lambda 时,`bind` 是必需的。现在它只是一个坐在角落里的怪物。从 c++14 开始它就完全过时了。 (2认同)
  • @bolov:不过,仅从 C++14 开始。这个问题被标记为 [tag:c++11],并且在 C++11 中,由于缺少泛型 lambdas,`std::bind` 在几种情况下更可取。请注意,这不是其中之一。我想这和你说的一样。 (2认同)