No matching function to call: error: must use ‘.*’ or ‘->*’ to call pointer-to-member function in ‘f (...)’, e.g. ‘(... ->* f) (...)’
No matching function to call: error: must use ‘.*’ or ‘->*’ to call pointer-to-member function in ‘f (...)’, e.g. ‘(... ->* f) (...)’
我正在尝试从线程池调用非静态成员函数。提交函数告诉我错误:必须使用‘.’或‘->’来调用‘f(...)’中的指向成员函数的指针,例如第一行的 std::future* f) (...)”。我试图不创建静态函数。我尝试了几种组合,但我认为我不明白它的要求。有人愿意帮忙吗?
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();
}
Compiler Output
更新:我changed auto submit(F&& f, Args&&... args) -> std::future<decltype(f(args...))>
到auto submit(F&& f, Args&&... args) -> std::future<std::invoke_result_t<F, Args...>>
现在我收到一个新的编译器错误“没有名为 'type' 的类型”。下图。
no type named 'type' compiler error
要正确获取调用成员函数或普通函数的结果类型,您必须使用 std::invoke_result_t
:
auto submit(F&& f, Args&&... args) -> std::future<std::invoke_result_t<F, Args...>> {
// ...
}
这样,成员函数和非成员函数都可以工作。
考虑发送成员函数时,必须同时传递实例:
// object of type MyClass -----v
submit(&MyClass::member_func, my_class, param1, param2);
我正在尝试从线程池调用非静态成员函数。提交函数告诉我错误:必须使用‘.’或‘->’来调用‘f(...)’中的指向成员函数的指针,例如第一行的 std::future
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();
}
Compiler Output
更新:我changed auto submit(F&& f, Args&&... args) -> std::future<decltype(f(args...))>
到auto submit(F&& f, Args&&... args) -> std::future<std::invoke_result_t<F, Args...>>
现在我收到一个新的编译器错误“没有名为 'type' 的类型”。下图。
no type named 'type' compiler error
要正确获取调用成员函数或普通函数的结果类型,您必须使用 std::invoke_result_t
:
auto submit(F&& f, Args&&... args) -> std::future<std::invoke_result_t<F, Args...>> {
// ...
}
这样,成员函数和非成员函数都可以工作。
考虑发送成员函数时,必须同时传递实例:
// object of type MyClass -----v
submit(&MyClass::member_func, my_class, param1, param2);