【问题标题】:Function/Method pointers Pushed to a Deque推送到双端队列的函数/方法指针
【发布时间】:2014-06-03 12:12:02
【问题描述】:

我正在为运行函数创建一个队列。我将需要调用的函数放入 std::deque<bool(*)()> 中,然后我在 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&lt;_Ty&gt;::push_back' : cannot convert parameter 1 from 'bool (__thiscall A2_Game::* )(void)' to 'bool (__cdecl *const &amp;)(void)'

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

【问题讨论】:

  • 您正在尝试将 成员函数指针 分配给原始函数指针。那行不通;)
  • 昆汀说了什么。编译器区分成员函数指针和原始函数指针。如果你想以同样的方式对待你的函数,我建议使用 std::function 和 std::bind。

标签: c++ function-pointers deque member-function-pointers


【解决方案1】:

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

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));

【讨论】:

  • 哦,我真希望我现在可以使用我的 c++11 编译器 :( 感谢您的指导
  • 你可以使用 boost::function 和 boost::bind 而不是 std::function 和 lambdas
  • 我也不能使用其他库:(
【解决方案2】:

问题是类方法的签名与函数签名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 标准中(请参阅 here),因此如果您的项目支持 C++11,只需使用 #include &lt;functional&gt; 和 std 而不是 boost 命名空间。

【讨论】:

    猜你喜欢
    • 2013-05-21
    • 2019-01-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-26
    • 2016-09-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多