函数/方法指针被压入Deque

Function/Method pointers Pushed to a Deque

本文关键字:Deque 指针 方法 函数      更新时间:2023-10-16

我正在为运行函数制作队列。我把需要调用的函数放到一个std::deque<bool(*)()>中,然后我在deque中循环调用每个函数并让它运行,有时甚至根据返回值做一些事情。

我遇到的问题实际上是关于将这些函数放在deque内部。

我在一个叫做A2_Game的类中有这个队列。我也有一门叫做Button的课。

我的代码类似如下:

class Button
{
    bool DoInput();
}
class A2_Game
{
    std::deque<bool(*)()> Input_Functions;
    bool EnterName()
}
A2_Game::OtherMethod()
{
    Button* btn1 = new Button();
    Input_Functions.push_back(&A2_Game::EnterName); //The compiler told me to do this and it still won't compile the line..
    Input_Functions.push_back(btn1->DoInput);
    //Loop
}

我无法确定如何修复编译错误。我怀疑你们中的一些人可以直接告诉我需要做什么改变/做什么才能使它编译,通过查看我在这里展示的。如果为!true,那么这里是编译错误。

error C2664: 'std::deque<_Ty>::push_back' : cannot convert parameter 1 from 'bool (__thiscall A2_Game::* )(void)' to 'bool (__cdecl *const &)(void)'

error C3867: 'Button::Doinput': function call missing argument list; use '&Button::Doinput' to create a pointer to member

如果你想推回函数,你可以使用std::function(或boost,如果你的编译器不支持c++11)

std::deque<std::function<bool()> > function_list;
Button* btn1 = new Button();
function_list.push_back([this](){return EnterName();});
function_list.push_back([btn1](){return btn1->DoInput();});

确保当您从function_list调用lambda时,lambda中的所有内容仍然有效。

编辑:提高等效

std::deque<boost::function<bool()> > function_list;
Button* btn1 = new Button();
function_list.push_back(boost::bind(&A2_Game::EnterName,this));
function_list.push_back(boost::bind(&Button::DoInput,btn1));

问题是类方法的签名与函数签名bool (*)()不匹配。两种方法的签名分别为bool (Button::*)();bool (A2_Game::*)();。(方法所属的实际类是其签名的一部分!)

这里的解决方案是使用函子/函数对象。函函数是围绕"可调用元素"的包装对象,如果您想将函数视为对象(在OOP意义上),它很有用。如果您手头有boost,您的代码可能看起来像这样(代码编译):
#include <boost/function.hpp>
#include <deque>
class Button
{
public:
    bool DoInput() { return true; }
};
class A2_Game
{
public:
    typedef boost::function<bool()> Functor;
    std::deque<Functor> Input_Functions;
    bool EnterName() { return true; }
    void OtherMethod();
};
void A2_Game::OtherMethod()
{
    Button* btn1 = new Button();
    Input_Functions.push_back(boost::bind(&A2_Game::EnterName, this));
    Input_Functions.push_back(boost::bind(&Button::DoInput, btn1));
}

boost::bind将函数指针与对实际类实例的引用结合在一起,并返回与A2_Game::Functor相同类型的函数对象。

请注意,boost::function已经集成到c++ 11标准中(见这里),所以如果您的项目支持c++ 11,只需使用#include <functional>std而不是boost命名空间。