Pase el contenido de la tupla como argumentos de función variable
Juego con C ++ 0x durante algún tiempo y ahora quiero usar plantillas y tuplas variadas para implementar la clase "Tarea". Voy a pasar objetos de Tarea a hilos recién creados (usando pthread). La clase de tarea contendrá un puntero de función a función que debería llamarse dentro del hilo y argumentos para esta función, código simplificado:
class TaskCaller
{
// ...
virtual bool dispatch (void);
};
template<typename ...T_arguments> Task :
public TaskCaller
{
public:
// ...
Task (bool (*function) (T_arguments&...),
T_arguments... arguments) :
function_arguments_tuple (arguments...),
function (function)
{
// ...
}
bool dispatch (void)
{
return TupleUnpack<sizeof ...(T_arguments)>::unpack (this->function, this->function_arguments_tuple);
}
private:
std::tuple<T_arguments&...> function_arguments_tuple;
bool (*function) (T_arguments...);
};
Y el código que uso para descomprimir la tupla en argumentos de función:
template<unsigned int i> class TupleUnpack
{
public:
template<typename T_return_type, typename ...T_tuple_arguments, typename ...T_function_arguments>
inline static T_return_type unpack (T_return_type (*function) (T_tuple_arguments&...),
std::tuple<T_tuple_arguments...>& arguments_tuple,
T_function_arguments ...function_arguments)
{
return TupleUnpack<i-1>::unpack (function, arguments_tuple, std::get<i-1> (arguments_tuple), function_arguments...);
}
};
template<> class TupleUnpack<0>
{
public:
template<typename T_return_type, typename ...T_tuple_arguments, typename ...T_function_arguments>
inline static T_return_type unpack (T_return_type (*function) (T_tuple_arguments&...),
std::tuple<T_tuple_arguments...>& arguments_tuple,
T_function_arguments ...function_arguments)
{
return function (function_arguments...);
}
};
Caso de uso:
bool task_function (Foo &foo, Bar &bar)
{
// ...
return true;
}
void* thread_function (void* argument)
{
Task* task ((Task*) argument);
task->dispatch ();
delete task;
pthread_exit (0);
}
void function (void)
{
Foo foo (1, 2, 3);
Bar bar (1, 2, 3);
Task<Foo, Bar>* task = new Task (task_function, std::move (foo) std::move (bar));
pthread_t thread_id;
pthread_create (&thread_id, task_function, task);
}
No he probado este código todavía, es solo una idea.
Ahora me pregunto cómo la clase TupleUnpack afectará el código final. Según mi conocimiento, la implementación final de la función Task :: dispatch (después de las plantillas de análisis del compilador) será equivalente a:
template<typename ...T_arguments> static bool Task<...T_arguments>::dispatch (void)
{
return this->function (std::get<0> (this->function_arguments_tuple), std::get<1> (this->function_arguments_tuple), ..., std::get<n> (this->function_arguments_tuple));
}
¿derecho?
Además, la tupla misma y std :: get () deberían "desaparecer" en el código final y no proporcionar sobrecarga en tiempo de ejecución(según la documentación de Boost).
Tal vez hay una mejor manera de resolver mi problema ...