我试图为我的引擎建立一个事件系统。我有一个想法,就是把指向我希望事件执行的函数的指针存储在事件结构中,但到目前为止我还没有成功。我对通过参数将函数传递给其他函数是一个全新的概念。
我设法拼凑出这个:
decltype(auto) _funcExec(Function&& func, Args&&...args)
{
return std::forward<Function>(func)(std::forward<Args>(args)...);
}
字符串
但是这只允许我通过_funcExec函数执行另一个函数。我需要以某种方式从这个中创建一个类型:(Function&& func, Args&&...args)
,这样我就可以创建一个Event结构体的指针成员,并将指针存储到我希望Event结构体执行的函数。
这个概念是这样的:
struct sEvent {
std::vector<sEventArg> arg;
std::function<void()> _storedFunc;
bool _funcStored = false;
template <class Function, class ... Args>
bool storeFunc(Function&& func, Args&&...args)
{
if( _funcStored ) return false;
_storedFunc = std::forward<Function>(func)(std::forward<Args>(args)...);
_funcStored = true;
return true;
}
auto executeFunc( void )
{
if( !_funcStored ) return error();
return _storedFunc(arg[0].get_int32(), arg[1].get_float); // no instance matches the argument list
}
};
型
事件被创建,存储在一个队列中,当时间到来时,它执行在创建时传递给它的函数。许多事件可以用不同的函数来创建执行。目标不是为引擎中的每个函数多写两个函数(setter for event,和event exec),我想通过事件系统来执行。
我希望我解释得很全面。
所以我有两个问题...
1.这有可能吗?如果有
1.怎么做?:D
谢谢
啊哈哈哈哈..答案沿着都在那里!这应该可行..
struct sEvent {
std::function<void()> _storedFunc;
template <typename Function, typename ...Args>
bool storeFunc( Function&& func, Args&&...args )
{
_storedFunc = std::function<void()>{ [=]() { func( args... ); } };
return true;
}
auto _execFunc( void )
{
return _storedFunc();
}
};
型
感谢大家,特别感谢泰德·林莫和463035818_is_not_an_ai
编辑:所以在玩了两天之后,我不能给这个提供任何函数,有参数,没有参数,void,auto,什么都没有:(
1条答案
按热度按时间ztyzrc3y1#
正如在注解中提到的,你可以把函数+参数变成一个
std::function<void()>
。你遗漏了很多细节,使用你提供的代码,你可以把它变成下面的东西来存储std::function
s的某个地方:字符串
Live Demo