gpt4 book ai didi

c++ - 没有匹配的函数要调用:错误:必须使用 ‘.*’或 ‘->*’来调用 ‘f (…)’中的指针成员函数,例如 ‘(… ->* f) (…)’

转载 作者:行者123 更新时间:2023-12-01 14:52:09 26 4
gpt4 key购买 nike

我正在尝试从线程池中调用非静态成员函数。提交功能告诉我错误:必须使用“。”或“->”来调用“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);

关于c++ - 没有匹配的函数要调用:错误:必须使用 ‘.*’或 ‘->*’来调用 ‘f (…)’中的指针成员函数,例如 ‘(… ->* f) (…)’,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62642158/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com