I'd like to have some abstraction Task class that can take any function or some object method (along with its arguments etc) and store it for later execution or distribute it on some threads, whatever.
I have experimented a bit with std::function but havent succeed. So I'd like to make it work or get familiar with some more efficient pattern for my needs.
#include <iostream>
#include <string>
#include <queue>
#include <memory>
#include <functional>
class ITask
{
public:
virtual ~ITask() = default;
virtual void execute() = 0;
};
template<typename ReturnType, typename... Args>
class GameTask : ITask
{
explicit GameTask(std::function<ReturnType(Args...)>& func) :
func_(func)
{}
void execute()
{
// func(Args...); ??
}
private:
std::function<ReturnType(Args...)> func_;
};
// lets imitate some bigger classes with various methods
class BigClassA
{
public:
void func1(int a) { std::cout << ++a; }
int func2(const std::string& s) { std::cout << s; return b; }
int b = 4;
};
class BigClassB
{
public:
double func1(BigClassA& bca, int i) { bca.b += i; return 0.1; }
};
int main()
{
BigClassA a;
BigClassB b;
// perform immidiately by current main thread:
a.func1(2);
b.func1(a, 3);
a.func2("Hello");
//store under queue for later execution
std::queue<std::unique_ptr<ITask>> queue;
/* a.func1(2); */
// queue.push(std::make_unique<GameTask>( [&a](){ a.func1(2); } ));
/* b.func1(a, 3); */
// queue.push(std::make_unique<GameTask>( ));
/* a.func2("Hello"); */
// queue.push(std::make_unique<GameTask>( ));
while (queue.size())
{
queue.front()->execute();
queue.pop();
}
}
Aucun commentaire:
Enregistrer un commentaire