c++ - 无法从C++中的抽象类绑定(bind)函数

标签 c++ function c++11 abstract-class stdbind

我尝试在抽象类中将 std::bind 与虚拟纯函数一起使用,但是 我使用设计模式调用策略,因为我想制作一个可以处理游戏之间动态切换的程序。

我不明白语法。这是代码:

这是我的接口(interface)类

class IGame
{
  public:
    virtual ~IGame(){};
    virtual void move_up(INFO &info)=0;
}

顺便说一句,INFO 是一个定义:

 #define INFO std::pair<struct GetMap*, struct WhereAmI*>

这是我调用 std::bind 调用的构造函数中的控制类;

 class CGame
  {
  private:
    IGame                                       *game;
    int                                         score;
    std::pair<struct GetMap*, struct WhereAmI*> info; // game information

    std::vector<std::function<void(std::pair<struct GetMap*, struct WhereAmI*>&)>> ptr_move_ft; //function pointer vector

  public:
    CGame();
    ~CGame();
    void return_get_map(INFO &info);
  }

这是CGame类的构造函数:

CGame::CGame()
 {
   game = new Snake();
   this->info = std::make_pair(init_map(MAP_PATH_SNAKE,0), game->init_player());

   ptr_move_ft.push_back(std::bind(&CGame::return_where_i_am, this,std::placeholders::_1)); //this work

   ptr_move_ft.push_back(std::bind(&game->move_up, game, std::placeholders::_1)); //this create a error
 }

所以第二个 push_back 会出现这个错误:

source/CGame.cpp: In constructor ‘arcade::CGame::CGame()’:
source/CGame.cpp:131:44: error: ISO C++ forbids taking the address of a bound member function to form a pointer to member function.  Say ‘&arcade::IGame::move_up’ [-fpermissive]
     ptr_move_ft.push_back(std::bind(&game->move_up, game, std::placeholders::_1));

我该怎么做?

对不起我糟糕的英语和 C++ 代码。

最佳答案

问题是表达式 &game->move_up在这一行中:

ptr_move_ft.push_back(std::bind(&game->move_up, game, std::placeholders::_1));

此表达式试图创建指向成员函数的指针,但这些指针未绑定(bind)到特定实例。因此,从特定实例创建指向成员函数的指针是没有意义的,类似于尝试通过实例调用静态方法。

而不是 &game->move_up你应该使用 &IGame::move_up .

您还可以使用 &std::decay<decltype(*game)>::type::move_up .优点是这个表达式会调整以匹配 *game 的类型, 寻找名为 move_up 的实例方法无论指向的类型是什么。缺点是语法有点迟钝。

(Here is a demo 展示了这两种方法如何产生相同的指向成员函数的指针。)

关于c++ - 无法从C++中的抽象类绑定(bind)函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43053615/

相关文章:

c++ - int * & 有实际意义吗?

python - 使用 XMLRPC 在 Python 中进行动态函数调用

c++ - 标准在哪里定义了将值绑定(bind)到引用的优先顺序?

c++ - std::async 与 std::promise

c++ - 在滚动窗口上应用矩阵乘法的最聪明方法

c++ - 为什么cmake没有定义这个宏?

C 将指针赋给 NULL

c++ - 使用移动的 std::string 的 .data() 成员不适用于小字符串?

c++ - C++1z 中的§12.3.2 [class.conv.fct]/1 相对于 C++14 发生了重大变化。是否有意义?

c++ - 使用Quazip构建c++ Qt CLI工具