问题描述
我正在编写代码以将函数指针存储在函数指针向量中。但是在我的实现中,我将要存储在向量中的函数是作为指针存储在另一个 std::map 中的类的成员函数。下面是代码片段。
class img_preprocess(){
public:
std::vector<void(*)(int)> receivers;
}
class detector(){
public:
void push(int val) {
//some code here
}
class tracker(){
private:
std::map< int,img_preprocess* > img_actors;
std::map< int,detector* > detect_actors;
public:
tracker(){
this->img_actors.insert({ 1,new img_preprocess() });
this->detect_actors.insert({ 1,new detector() });
// adding the detector::push function to img_preprocess receivers vector
this->img_actors[1]->receivers.push_back(
& ( this->detect_actors[1]->push ) // this line gives me the error
)
}
}
我的目的是在 img_preprocess 对象的接收者向量中保留一个检测器对象的推送函数的函数指针。 上述方法给了我 一个指向绑定函数的指针可能仅用于调用函数错误。关于如何克服此错误并实现我的意图的任何想法?
编辑 01:
就我而言,我必须在接收者向量中存储几个推送函数。这些推送函数是像检测器这样的类的成员(例如:matcher::push、distributor::push)
class Matcher{
public:
void push(int val){
//some code here
}
}
class distributor{
public:
void push(int val){
//some code here
}
}
解决方法
使用std::function
。
详细了解 here
C++ 中的类定义不应该是这样的:class img_preprocess()
。前面的 () 会触发语法错误。非继承、非模板化的类定义通常遵循这种格式。
class ClassName
{
/* Class members go here. */
};
处理成员函数指针时,vector的value_type
应该是成员函数类型。在您的情况下,成员函数类型是 void (detector::*)(int)
。
typedef void (detector::*FuncT)(int);
class img_preprocess {
public:
std::vector<FuncT> receivers;
}
并且在添加成员函数指针时,不能使用对象实例将其添加到向量中。您必须使用 ::
运算符。
this->img_actors[1]->receivers.push_back(&(detector::push));
现在打电话时,
(this->detect_actors[1]->(*this->img_actors[1]->receivers[/* whatever the index */]))(/* whatever the argument */);
现在将所有内容放在一起,您的最终代码将如下所示。
class detector; // Forward declaration needed for the typedef and img_preprocess object.
typedef void(detector::* FuncT)(int);
class img_preprocess {
public:
std::vector<FuncT> receivers;
};
class detector {
public:
void push(int val) {
//some code here
}
};
class tracker {
private:
std::map< int,img_preprocess* > img_actors;
std::map< int,detector* > detect_actors;
public:
tracker() {
this->img_actors.insert({ 1,new img_preprocess() });
this->detect_actors.insert({ 1,new detector() });
// adding the detector::push function to img_preprocess receivers vector
this->img_actors[1]->receivers.push_back(&(detector::push));
}
};
编辑:如果要存储除detactor
之外的其他对象的成员函数指针,可以使用std::function
和std::bind
向向量添加成员函数指针,
#include <functional> // For std::function and std::bind
class img_preprocess {
public:
std::vector<std::function<void(int)>> receivers;
};
...
this->img_actors[1]->receivers.push_back(std::bind(&detector::push,this->detect_actors[1],std::placeholders::_1)); // Adding the function pointer to the vector.
this->img_actors[1]->receivers[0](5); // When calling the function.
附加:Using generic std::function objects with member functions in one class