I'm trying to put together an Event system for my engine. I had the idea of storing pointer to the function I want the Event to execute inside the Event struct, but so far I was unsucessfull. I'm completely new to passing functions through arguments to other functions.
I managed to put together this:
decltype(auto) _funcExec(Function&& func, Args&&...args)
{
return std::forward<Function>(func)(std::forward<Args>(args)...);
}
But that only allows me to execute another function through the _funcExec function..
I need to somehow make a type out of this: (Function&& func, Args&&...args)
so I can make a pointer member of my Event struct and store the pointer to the function I want the Event struct to execute..
And the concept is something like this:
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
}
};
Event is created, stored in a queue and when the time comes it executes the function that was passed to it at creation time. Many events can be created with different functions to execute. The goal is not to write two more functions(setter for event, and event exec) for every function in the engine I want to be executable through the Event system..
I hope I explained it comprehensively.
So I have two questions..
Thank you.
Ahaaahaha.. the answer was there all along! This should work..
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();
}
};
Thank you all and especially to @Ted Lyngmo and @463035818_is_not_an_ai
Edit: So after two days playing with it I was not able to feed this any functions, with arguments, without args, void, auto, nothing :(
As mentioned in a comment, you can turn function + arguments into a std::function<void()>
. You left out many details, using the code you did provide, you can turn it into the following to store the std::function
s somewhere:
#include <iostream>
#include <functional>
template <typename Function, typename ...Args>
auto make_function(Function&& func, Args&&...args)
{
return std::function<void()>{
[=](){ func(args...); }
};
}
void foo() { std::cout << "foo\n" ;}
void bar(int x) { std::cout << "bar" << x << "\n"; }
int main() {
auto f = make_function(foo);
f();
auto g = make_function(bar,42);
g();
}