I'm trying to call a non-static member function from a thread pool. The submit function tells me error: must use '. ' or '-> ' to call pointer-to-member function in 'f (...)', eg '(... ->* f) (...)' for the std::future<decltype(f(args...)) portion on the first line. I'm trying to not create a static function. I've tried a few combinations but I don't think I understand what it is asking for. Would anyone help?
auto submit(F&& f, Args&&... args) -> std::future<decltype(f(args...))> {
// Create a function with bounded parameters ready to execute
std::function<decltype(f(args...))()> func = std::bind(std::forward<F>(f), std::forward<Args>(args)...);
// Encapsulate it into a shared ptr in order to be able to copy construct / assign
auto task_ptr = std::make_shared<std::packaged_task<decltype(f(args...))()>>(func);
// Wrap packaged task into void function
std::function<void()> wrapper_func = [task_ptr]()
{
(*task_ptr)();
};
// Enqueue generic wrapper function
m_queue.enqueue(wrapper_func);
// Wake up one thread if its waiting
m_conditional_lock.notify_one();
// Return future from promise
return task_ptr->get_future();
}
Update: I changed auto submit(F&& f, Args&&... args) -> std::future<decltype(f(args...))>
to auto submit(F&& f, Args&&... args) -> std::future<std::invoke_result_t<F, Args...>>
Now I'm getting a new compiler error "no type named 'type'". Picture below.
To correctly get the result type of a call to a member function or a normal function you must use std::invoke_result_t
:
auto submit(F&& f, Args&&... args) -> std::future<std::invoke_result_t<F, Args...>> {
// ...
}
That way, both member function and non member function will work.
Consider that when sending a member function, you must also pass the instance:
// object of type MyClass -----v
submit(&MyClass::member_func, my_class, param1, param2);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.