Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/138.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 如何创建<;id,成员函数>;?_C++ - Fatal编程技术网

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
“有错误”。请发布错误消息。@JesperJuhl
std::function
本身仍然会有同样的问题,您需要将成员函数应调用的对象与该函数连接起来。因此,不必提及
std::bind
,这并没有真正的帮助。@t.niese当然,您需要
std::bind
或lambda when向地图添加条目。但这并不十分困难。