Skip to content

Instantly share code, notes, and snippets.

@zhangyuchi
Created December 19, 2014 04:33
Show Gist options
  • Save zhangyuchi/8af4d6e38964df2cc019 to your computer and use it in GitHub Desktop.
Save zhangyuchi/8af4d6e38964df2cc019 to your computer and use it in GitHub Desktop.
perfect task function
template<typename ... MTArg>
struct Task {
typedef void (*RawFunction)(MTArg...);
//Here we want to forward some set of arguments into a tuple, but the arguments need not match MTArg -- they just have to be convertible:
template<typename ... Args>
explicit Task(RawFunction rawFunction, Args&&... args)
rawFunction(rawFunction),
args(std::make_tuple(std::forward<Args>(args)...)) {}
//which the above checks. Note I made it explicit, as if Args... is empty, we don't want this to be a converting constructor.
void run() {
callFunction(GenIndexSequence<sizeof...(MTArg)>());
}
private:
template<unsigned int... argIndexs>
inline void callFunction() {
rawFunction(std::forward<MTArg>(std::get<argIndexs>(args))...);
}
RawFunction rawFunction;
std::tuple<MTArg...> args;
};
//and then we write a make_task function:
template<typename ... MTArg, typename... Args>
Task<MTArg...> make_task( void(*raw)(MTArg...), Args...&& args ) {
return { raw, std::forward<Args>(args)... };
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment