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()>' (即使我并没有真正调用该函数)对于每个备用编译。
如何在向量中存储函数或函数指针?编译器试图传达什么?
您的示例中有两个问题。
bool更改为function<bool>。只需将其保留为bool,因为这是您想要的返回类型。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)