函数/方法指针被压入Deque
Function/Method pointers Pushed to a Deque
我正在为运行函数制作队列。我把需要调用的函数放到一个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::*)();
。(方法所属的实际类是其签名的一部分!)
#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
命名空间。
- 1d 智能指针不适用于语法 (*)++
- 在C#中处理C++指针而不使用unsafe的最佳方法
- 为什么使用 "this" 指针调用派生成员函数?
- 函数向量_指针有不同的原型,我可以构建一个吗
- 使用指针从C++中的数组中获取最大值
- 助记符和指向成员语法的指针
- 嵌入方指针压缩已禁用
- 数组的指针从不分段故障
- C++ 指针的内存地址和指向数组的内存地址如何相同?
- 何时在引用或唯一指针上使用移动语义
- QMetaObject invokeMethod的基于函数指针的语法
- 如何从 std::atomic 中提取指针 T<T>?
- Deque指针内存泄漏
- deque中指针的自定义比较器
- 空的deque与未使用的指向deque的指针
- New和delete操作符不影响指向该类的指针的Deque的内容
- 如何获取指向原始数据的std::deque指针
- 函数/方法指针被压入Deque
- 将deque转换为void指针是否安全
- Deque emplace_back指向对象的新指针