【发布时间】:2021-06-03 19:42:27
【问题描述】:
我正在编写代码以将函数指针存储在函数指针向量中。但在我的实现中,我要存储在向量中的函数是一个类的成员函数,它作为指针存储在另一个 std::map 中。下面是代码sn-p。
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 对象的接收器向量内为检测器对象的 push 函数保留一个函数指针。上述方法为我提供了 一个指向绑定函数的指针仅用于调用函数错误。关于如何克服这个错误并实现我的意图的任何想法?
编辑 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
}
}
【问题讨论】:
-
松散相关,您可能对type erasure感兴趣。
-
指向成员函数的指针非常不同。已经有很多重复了。如果不需要访问对象数据,则将函数设为静态,或者您必须将对象附加到它
标签: c++ c++11 pointers function-pointers member-function-pointers