multithreading - C++11 std::thread accepting function with rvalue parameter -
i have homework, , have troubles understanding, (probably) how passing parameters std::thread constructor works.
assume following code (i deleted unneeded parts)
template<typename t, typename task> class scheduler { private: typedef std::unordered_map<std::size_t, t> results; class solver { public: solver(task&& task) : m_thread(&solver::thread_function, std::move(task)) { m_thread.detach(); } solver(solver&& solver) = default; // required vector::emplace_back ~solver() = default; private: void thread_function(task&& task) { task(); } std::thread m_thread; }; public: scheduler() = default; ~scheduler() = default; void add_task(task&& task) { m_solvers.emplace_back(std::move(task)); } private: std::vector<solver> m_solvers; }; template<typename t> struct ftor { explicit ftor(const t& t) : data(t) { } t operator()() { std::cout << "computed" << std::endl; return data; } t data; }; int main() { scheduler<int, ftor<int>> scheduler_ftor; scheduler<int, std::function<int(void)>> scheduler_lambda; ftor<int> s(5); scheduler_ftor.add_task(std::move(s)); scheduler_lambda.add_task([](){ std::cout << "computed" << std::endl; return 1; }); }
why doesn't compile? mvs2015 complaining about
functional(1195): error c2064: term not evaluate function taking 1 arguments functional(1195): note: class not define 'operator()' or user defined conversion operator pointer-to-function or reference-to-function takes appropriate number of arguments
note: while compiling class template member function 'scheduler<int,ftor<int> >::solver::solver(task &&)'
while g++ 4.9.2
functional: in instantiation of ‘struct std::_bind_simple<std::_mem_fn<void (scheduler<int, ftor<int> >::solver::*)(ftor<int>&&)>(ftor<int>)>’:
required ‘void scheduler<t, task>::add_task(task&&) [with t = int; task = ftor<int>]’functional:1665:61: error: no type named ‘type’ in ‘class std::result_of<std::_mem_fn<void (scheduler<int, ftor<int> >::solver::*)(ftor<int>&&)>(ftor<int>)>’ typedef typename result_of<_callable(_args...)>::type result_type;
i suppose there problems std::moving std::thread.
if use member function first thread argument, second argument supposed pointer, pointing object member function called to
update
good discussion here
Comments
Post a Comment