C++ 如何创建<;id,成员函数>;?
在下面的代码中,我创建了指向成员函数的指针映射C++ 如何创建<;id,成员函数>;?,c++,C++,在下面的代码中,我创建了指向成员函数的指针映射 class A { public: A() { m[0] = &A::F1; m[1] = &A::F2; } void F1(int v) { ... } void F2(int v) { ... } void O(int i, int v) { (*m[i])(v); } private: using func = void(A::*)(int); std::map&
class A {
public:
A() {
m[0] = &A::F1;
m[1] = &A::F2;
}
void F1(int v) { ... }
void F2(int v) { ... }
void O(int i, int v) {
(*m[i])(v);
}
private:
using func = void(A::*)(int);
std::map<int, func> m;
};
A类{
公众:
(){
m[0]=&A::F1;
m[1]=&A::F2;
}
void F1(int v){…}
空F2(int v){…}
无效O(整数i,整数v){
(*m[i])(v);
}
私人:
使用func=void(A::*)(int);
std::map m;
};
但是“O”中有一个编译错误。在我的理解中,“m[i]”是一个指向成员函数的指针,(*m[i])取消对它的引用,并应调用相应的成员函数。但它不起作用
- 你能帮我解释一下吗
- 是否有其他简洁的方法来创建成员函数的映射
(this->*m[i])(v);
另一种方法是使用
std::function
,例如:
class A {
public:
A() { // implicit capture of this is deprecated in c++20
m[0] = [this](int v) { F1(v); };
m[1] = [this](int v) { F2(v); };
}
void F1(int v) { std::cout << "F1: " << v; }
void F2(int v) { std::cout << "F2: " << v; }
void O (int i, int v) { m[i](v); }
private:
std::map<int, std::function<void(int)>> m;
};
int main() {
A a;
a.O(0, 5);
}
A类{
公众:
c++20中不推荐使用(){//隐式捕获
m[0]=[this](intv){F1(v);};
m[1]=[this](intv){F2(v);};
}
void F1(int v){std::cout您可以使用std::map
“有错误”。请发布错误消息。@JesperJuhlstd::function
本身仍然会有同样的问题,您需要将成员函数应调用的对象与该函数连接起来。因此,不必提及std::bind
,这并没有真正的帮助。@t.niese当然,您需要std::bind
或lambda when向地图添加条目。但这并不十分困难。