我想实现一个“任务”类,它可以存储一个函数指针以及一些要传递给它的参数。像 std::bind()。我对如何存储参数有一些疑问。
class BaseTask {
public:
virtual ~BaseTask() {}
virtual void run() = 0;
};
template<typename ... MTArg>
class Task : public BaseTask {
public:
typedef void (*RawFunction)(MTArg...);
Task(RawFunction rawFunction, MTArg&& ... args) : // Q1: MTArg&& ... args
rawFunction(rawFunction),
args(std::make_tuple(std::forward<MTArg>(args)...)) {} // Q2: std::make_tuple(std::forward<MTArg>(args)...)
virtual void run() {
callFunction(GenIndexSequence<sizeof...(MTArg)>()); // struct GenIndexSequence<count> : IndexSequence<0, ..., count-1>
}
private:
template<unsigned int... argIndexs>
inline void callFunction() {
rawFunction(std::forward<MTArg>(std::get<argIndexs>(args))...);
}
private:
RawFunction rawFunction;
std::tuple<MTArg...> args; // Q3: std::tuple<MTArg...>
};
Q1:MTArg 之后是否需要 &&
Q2:这种方式对 init args 是否正确
Q3:args 的类型是否正确,我需要:
std::tuple<special_decay_t<MTArg>...>
根据这个:http ://en.cppreference.com/w/cpp/utility/tuple/make_tuple
// 问题结束
我希望 Task 可以这样使用:
void fun(int i, const int& j) {} BaseTask* createTask1() { return new Task<int, const int&>(&fun, 1, 2); // "2" must not be disposed at the time of task.run(), so inside Task "2" should be store as "int", not "const int&" } BaseTask* createTask2(const int& i, const int& j) { return new Task<int, const int&>(&fun, i, j); // "j" must not be disposed at the time of task.run(), so inside Task "j" should be store as "int", not "const int&" } void test(){ createTask1()->run(); createTask2(1, 2)->run(); }
任务只会运行一次,即零次或一次。