簡體   English   中英

沒有匹配的 function 來調用:錯誤:必須使用 '.*' 或 '->*' 來調用指向成員 function 在 'f (...)' 中的指針,例如 '(... ->* f) (...)'

[英]No matching function to call: error: must use ‘.*’ or ‘->*’ to call pointer-to-member function in ‘f (…)’, e.g. ‘(… ->* f) (…)’

我正在嘗試從線程池中調用非靜態成員 function。 提交 function 告訴我錯誤:必須使用 '. ' 或 '-> ' 在 'f (...)' 中調用指向成員 function 的指針,例如 std::future<decltype( f(args...)) 部分在第一行。 我試圖不創建 static function。 我嘗試了一些組合,但我認為我不明白它的要求。 有人會幫忙嗎?

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();
    }

編譯器 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'的類型”。 下圖。

沒有名為“類型”的類型編譯器錯誤

要正確獲取對成員 function 或普通 function 的調用的結果類型,您必須使用std::invoke_result_t

auto submit(F&& f, Args&&... args) -> std::future<std::invoke_result_t<F, Args...>> {
    // ...
}

這樣,成員 function 和非成員 function 都可以工作。

考慮發送成員 function 時,還必須傳遞實例:

// object of type MyClass -----v
submit(&MyClass::member_func, my_class, param1, param2);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM