I am working on a small program that executes action sequentially using an action queue.
I would like to be able to store parameters in my actions until they are executed (parameters should then be accessible from the exec()
method of the action).
I have a small example below :
#include <tuple>
#include <iostream>
#include <memory>
#include <utility>
#include <queue>
/**
* Action interface
*/
struct Action {
Action() {}
virtual void exec() = 0;
};
/**
* This action creates an object which type is given as template
* and passes the parameters given to its ctor. On completion, it
* prints its ID.
*/
template<class T, class... Ps>
struct CustomAction : public Action {
// trying to store the variable arguments
std::tuple<Ps...> _args;
int _actionId;
CustomAction(int id, Ps&&... args) : _actionId(id),
_args(std::make_tuple(std::forward<Ps>(args)...)) {
}
virtual void exec() override {
T* item = new T(std::forward<Ps>(_args)...);
std::cout << "done " << _actionId << std::endl;
}
};
struct ActionQueue {
std::queue<Action*> _queue;
ActionQueue() {
}
void exec() {
while(_queue.size()) {
auto action = _queue.front();
action->exec();
_queue.pop();
}
}
template<class T, class... Ps>
void push(Ps&&... args) {
auto action = new T(std::forward<Ps>(args)...);
_queue.push(action);
}
};
/**
* Example item that is to be created. Nothing important here
*/
struct Item {
int _b;
Item(int b) : _b(b) {
}
};
int main() {
ActionQueue aq;
int actionId = 5;
int param = 2;
aq.push<CustomAction<Item>>(actionId, param);
// do stuff
aq.exec();
}
In this example, I create an ActionQueue
. I push a new CustomAction
in the queue. This action simply creates an Item
and gives its ctor the parameters that I had given when I pushed the action on the action queue.
My problem is that I don't know why the parameter given to the push()
method is not available to use in the CustomAction
class.
Compiling the above example gives me the following error :
<source>:56:27: error: no matching constructor for initialization of 'CustomAction<Item>'
auto action = new T(std::forward<Ps>(args)...);
^ ~~~~~~~~~~~~~~~~~~~~~~
<source>:82:8: note: in instantiation of function template specialization 'ActionQueue::push<CustomAction<Item>, int &, int &>' requested here
aq.push<CustomAction<Item>>(actionId, param);
^
<source>:27:5: note: candidate constructor not viable: requires single argument 'id', but 2 arguments were provided
CustomAction(int id, Ps&&... args) : _actionId(id),
^
<source>:22:8: note: candidate constructor (the implicit copy constructor) not viable: requires 1 argument, but 2 were provided
struct CustomAction : public Action {
^
<source>:22:8: note: candidate constructor (the implicit move constructor) not viable: requires 1 argument, but 2 were provided
1 error generated.
Compiler returned: 1
The error says that CustomAction
needs one parameter while two were given, but CustomAction
should accept the second argument in args
.
What am i doing wrong here ?
Thanks