簡體   English   中英

包裝std :: thread調用函數

[英]Wrap std::thread call function

我想控制threads ,因此每個新發出的thread將首先通過我的代碼。
這樣,在下面的示例中,每個由runThread()發出的新線程都將首先調用下面的函數runInnerThread() (在其中我進行某種初始化),然后調用所需的函數。

我試過把這樣的事情:

#include <iostream>
#include <thread>

template<typename _Callable, typename... _Args>
void runThreadInner(_Callable&& __f, _Args&&... __args) {
    // My initializations...
    __f(__args...);
    // My finishing...
};

template<typename _Callable, typename... _Args>
bool runThread(_Callable&& __f, _Args&&... __args) {
    std::thread t(std::bind(&runThreadInner,
                            std::forward<_Callable>(__f),
                            std::forward<_Args>(__args)...));
}

int main() {
    runThread([]() {
        std::cout << std::this_thread::get_id() << "Threading...\n";
    });
    return 0;
}

我從編譯器收到錯誤,抱怨推斷出runThreadInner()模板

main.cpp: In instantiation of ‘bool runThread(_Callable&&, _Args&& ...) [with _Callable = main()::__lambda0; _Args = {}]’:
main.cpp:43:3:   required from here
main.cpp:27:38: error: no matching function for call to ‘bind(<unresolved overloaded function type>, main()::__lambda0)’
        std::forward<_Args>(__args)...));
                                      ^
main.cpp:27:38: note: candidates are:
In file included from /usr/include/c++/4.8/memory:79:0,
                 from main.cpp:2:
/usr/include/c++/4.8/functional:1655:5: note: template<class _Func, class ... _BoundArgs> typename std::_Bind_helper<std::__or_<std::is_integral<typename std::decay<_Tp>::type>, std::is_enum<typename std::decay<_Tp>::type> >::value, _Func, _BoundArgs ...>::type std::bind(_Func&&, _BoundArgs&& ...)
     bind(_Func&& __f, _BoundArgs&&... __args)
     ^
/usr/include/c++/4.8/functional:1655:5: note:   template argument deduction/substitution failed:
main.cpp:27:38: note:   couldn't deduce template parameter ‘_Func’
        std::forward<_Args>(__args)...));
                                      ^
In file included from /usr/include/c++/4.8/memory:79:0,
                 from main.cpp:2:
/usr/include/c++/4.8/functional:1682:5: note: template<class _Result, class _Func, class ... _BoundArgs> typename std::_Bindres_helper<_Result, _Func, _BoundArgs>::type std::bind(_Func&&, _BoundArgs&& ...)
     bind(_Func&& __f, _BoundArgs&&... __args)
     ^
/usr/include/c++/4.8/functional:1682:5: note:   template argument deduction/substitution failed:
main.cpp:27:38: note:   couldn't deduce template parameter ‘_Result’
        std::forward<_Args>(__args)...));

我嘗試顯式定義模板,但沒有成功:

template<typename _Callable, typename... _Args>
bool runThread(_Callable&& __f, _Args&&... __args) {
    std::thread t(std::bind(&runThreadInner<_Callable, _Args>,
                            std::forward<_Callable>(__f),
                            std::forward<_Args>(__args)...));
}

可能嗎? 謝謝。

您可能缺少#include <functional> (其中已定義std::bind )。

但是,在您的情況下,實際上並不需要std::bind ,因為您有lambda,在許多方面都更好

這是一個沒有std::bind的工作示例:

#include <iostream>
#include <functional>
#include <thread>
#include <utility>

template <typename F>
struct MyTaskWrapper {
  F f;

  template <typename... T>
  void operator()(T&&... args) {
    std::cout << "Stuff before...\n";
    f(std::forward<T>(args)...);
    std::cout << "Stuff after...\n";
  }

};

template <typename F, typename... Args>
void runThread(F&& f, Args&&... args) {
  std::thread trd(MyTaskWrapper<F>{std::forward<F>(f)}, std::forward<Args>(args)...);
  trd.join();
}

int main() {
  runThread([] {
    std::cout << "Threading...\n";
  });
}

輸出:

Stuff before...
Threading...
Stuff after...

現場演示

十分簡單。

#include <thread>
#include <iostream>

template<typename Callable, typename... Args>
void runThreadInner(Callable&& f, Args&&... args) {
    // My initializations...
    f(args...);
    // My finishing...
};

template<typename Callable, typename... Args>
std::thread runThread(Callable&& f, Args&&... args) {
    std::thread t(&runThreadInner<Callable, Args...>, 
         std::forward<Callable> (f), std::forward<Args>(args)...);
    return t;
}
int main() {
    auto t = runThread([]() {
        std::cout << "Threading..." << std::endl;
    });
    t.join();
    return 0;
}

您的代碼有問題。 我幾乎拒絕代碼審查中的每一行。

_Capital不是合法的C ++。 __lower也不是。 停止復制system和std標頭所做的事情,不允許這樣做。 他們之所以這樣做, 恰恰是因為您現在可以保證他們的代碼不會與您執行愚蠢的預處理程序操作(以任何合法方式)重疊。

template<typename Callable>
std::thread runThread(Callable&& f) {
  std::thread t([=]{
    // My initializations...
    f();
    // My finishing...
  });
  return t;
}

int main() {
  auto t = runThread([]() {
    std::cout << std::this_thread::get_id() << "Threading...\n";
  });
  t.join();
}

如果有人想綁定參數,請讓他們自己在調用runThread時進行綁定。

錯誤:沒有匹配的 function 調用 'std::thread::_Invoker <std::tuple< div><div id="text_translate"><p> 我正面臨線程問題。</p><p> 我試圖在 Chronometer class 的線程內執行 function,包括一個 while 循環:</p><p> 這是部分代碼:</p><pre> for(int i = 0; i<car_data.size();i++) { if(car_data[i]->checkArea(frame, pt1_zone, pt2_zone)) { std::thread(&Chronometer::start_chrono, car_crono[i], std::ref(chrono)); cv::rectangle(frame, car_data[i]->pt1, car_data[i]->pt2, cv::Scalar(255,0,0), 1, cv::LINE_8,0); //cv::putText(frame, "Parked", car_data[i]->pt1, cv::FONT_HERSHEY_DUPLEX, 0.9, cv::Scalar( 50, 255, 50 )); //occupancy_state = place.occupancyTrue(); //place_1.occupancy = true;</pre><p> car_crono 和 chrono 的類型</p><pre>std::vector<Chronometer*> car_crono; Chronometer chrono;</pre><p> 這是我的 class 計時器:</p><pre> class Chronometer { private: static int hour, min, sec; //std::stringstream ss; //Chronometer chrono; public: Chronometer(); static Chronometer& start_chrono(Chronometer& chrono); static Chronometer& finish_chrono(Chronometer& chrono); friend std::ostream& operator<<(std::ostream& flux, Chronometer t); Chronometer& operator=(const Chronometer& other); ~Chronometer(); };</pre><p> 對於線程,我嘗試了幾種參數。 最后一個:</p><pre> std::thread(&Chronometer::start_chrono, car_crono[i], std::ref(chrono));</pre><p> 我猜 ref 是必要的,但沒有改變。</p><p> 這是完整的錯誤</p><pre>/usr/include/c++/7/thread: In instantiation of 'struct std::thread::_Invoker<std::tuple<Chronometer& (*)(Chronometer&), Chronometer*, std::reference_wrapper<Chronometer> > >': /usr/include/c++/7/thread:127:22: required from 'std::thread::thread(_Callable&&, _Args&&...) [with _Callable = Chronometer& (*)(Chronometer&); _Args = {Chronometer*&, std::reference_wrapper<Chronometer>}]' recognizer_rtsp.cxx:348:76: required from here /usr/include/c++/7/thread:240:2: error: no matching function for call to 'std::thread::_Invoker<std::tuple<Chronometer& (*)(Chronometer&), Chronometer*, std::reference_wrapper<Chronometer> > >::_M_invoke(std::thread::_Invoker<std::tuple<Chronometer& (*)(Chronometer&), Chronometer*, std::reference_wrapper<Chronometer> > >::_Indices)' operator()() ^~~~~~~~ /usr/include/c++/7/thread:231:4: note: candidate: template<long unsigned int..._Ind> decltype (std::__invoke((_S_declval<_Ind>)()...)) std::thread::_Invoker<_Tuple>::_M_invoke(std::_Index_tuple<_Ind...>) [with long unsigned int..._Ind = {_Ind...}; _Tuple = std::tuple<Chronometer& (*)(Chronometer&), Chronometer*, std::reference_wrapper<Chronometer> >] _M_invoke(_Index_tuple<_Ind...>) ^~~~~~~~~ /usr/include/c++/7/thread:231:4: note: template argument deduction/substitution failed: /usr/include/c++/7/thread: In substitution of 'template<long unsigned int..._Ind> decltype (std::__invoke(_S_declval<_Ind>()...)) std::thread::_Invoker<std::tuple<Chronometer& (*)(Chronometer&), Chronometer*, std::reference_wrapper<Chronometer> > >::_M_invoke<_Ind...>(std::_Index_tuple<_Ind1...>) [with long unsigned int..._Ind = {0, 1, 2}]': /usr/include/c++/7/thread:240:2: required from 'struct std::thread::_Invoker<std::tuple<Chronometer& (*)(Chronometer&), Chronometer*, std::reference_wrapper<Chronometer> > >' /usr/include/c++/7/thread:127:22: required from 'std::thread::thread(_Callable&&, _Args&&...) [with _Callable = Chronometer& (*)(Chronometer&); _Args = {Chronometer*&, std::reference_wrapper<Chronometer>}]' recognizer_rtsp.cxx:348:76: required from here /usr/include/c++/7/thread:233:29: error: no matching function for call to '__invoke(std::__tuple_element_t<0, std::tuple<Chronometer& (*)(Chronometer&), Chronometer*, std::reference_wrapper<Chronometer> > >, std::__tuple_element_t<1, std::tuple<Chronometer& (*)(Chronometer&), Chronometer*, std::reference_wrapper<Chronometer> > >, std::__tuple_element_t<2, std::tuple<Chronometer& (*)(Chronometer&), Chronometer*, std::reference_wrapper<Chronometer> > >)' -> decltype(std::__invoke(_S_declval<_Ind>()...)) ~~~~~~~~~~~~~^~~~~~~~~~~~~~~~~~~~~~~ In file included from /usr/include/c++/7/tuple:41:0, from /usr/include/c++/7/bits/stl_map.h:63, from /usr/include/c++/7/map:61, from../alpr_utils.h:7, from recognizer_rtsp.cxx:34: /usr/include/c++/7/bits/invoke.h:89:5: note: candidate: template<class _Callable, class... _Args> constexpr typename std::__invoke_result<_Functor, _ArgTypes>::type std::__invoke(_Callable&&, _Args&&...) __invoke(_Callable&& __fn, _Args&&... __args) ^~~~~~~~ /usr/include/c++/7/bits/invoke.h:89:5: note: template argument deduction/substitution failed: /usr/include/c++/7/bits/invoke.h: In substitution of 'template<class _Callable, class... _Args> constexpr typename std::__invoke_result<_Functor, _ArgTypes>::type std::__invoke(_Callable&&, _Args&&...) [with _Callable = Chronometer& (*)(Chronometer&); _Args = {Chronometer*, std::reference_wrapper<Chronometer>}]': /usr/include/c++/7/thread:233:29: required by substitution of 'template<long unsigned int..._Ind> decltype (std::__invoke(_S_declval<_Ind>()...)) std::thread::_Invoker<std::tuple<Chronometer& (*)(Chronometer&), Chronometer*, std::reference_wrapper<Chronometer> > >::_M_invoke<_Ind...>(std::_Index_tuple<_Ind1...>) [with long unsigned int..._Ind = {0, 1, 2}]' /usr/include/c++/7/thread:240:2: required from 'struct std::thread::_Invoker<std::tuple<Chronometer& (*)(Chronometer&), Chronometer*, std::reference_wrapper<Chronometer> > >' /usr/include/c++/7/thread:127:22: required from 'std::thread::thread(_Callable&&, _Args&&...) [with _Callable = Chronometer& (*)(Chronometer&); _Args = {Chronometer*&, std::reference_wrapper<Chronometer>}]' recognizer_rtsp.cxx:348:76: required from here /usr/include/c++/7/bits/invoke.h:89:5: error: no type named 'type' in 'struct std::__invoke_result<Chronometer& (*)(Chronometer&), Chronometer*, std::reference_wrapper<Chronometer> >'</pre><p> 我應該通過線程傳遞什么樣的參數?</p><p> 我去了幾個鏈接來尋找解決方案,但沒有什么能解決我的問題:</p><p> <a href="https://stackoverflow.com/questions/21048906/stdthread-pass-by-reference-calls-copy-constructor" rel="nofollow noreferrer">std::thread 通過引用傳遞調用復制構造函數</a></p><p> <a href="https://stackoverflow.com/questions/67625058/no-matching-function-to-invoke-using-stdthread" rel="nofollow noreferrer">沒有匹配的 function 調用,使用 std::thread</a></p><p> ... </p></div></std::tuple<>

[英]error: no matching function for call to ‘std::thread::_Invoker<std::tuple

暫無
暫無

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

相關問題 在不同的線程中調用std :: function 如何包裝對std :: thread構造函數的調用? (適用於gcc,VS和icpc) 錯誤:沒有用於調用 std::thread 的匹配函數 使用std :: async從線程進行函數調用? 錯誤:沒有匹配的 function 調用 'std::thread::_Invoker <std::tuple< div><div id="text_translate"><p> 我正面臨線程問題。</p><p> 我試圖在 Chronometer class 的線程內執行 function,包括一個 while 循環:</p><p> 這是部分代碼:</p><pre> for(int i = 0; i<car_data.size();i++) { if(car_data[i]->checkArea(frame, pt1_zone, pt2_zone)) { std::thread(&Chronometer::start_chrono, car_crono[i], std::ref(chrono)); cv::rectangle(frame, car_data[i]->pt1, car_data[i]->pt2, cv::Scalar(255,0,0), 1, cv::LINE_8,0); //cv::putText(frame, "Parked", car_data[i]->pt1, cv::FONT_HERSHEY_DUPLEX, 0.9, cv::Scalar( 50, 255, 50 )); //occupancy_state = place.occupancyTrue(); //place_1.occupancy = true;</pre><p> car_crono 和 chrono 的類型</p><pre>std::vector<Chronometer*> car_crono; Chronometer chrono;</pre><p> 這是我的 class 計時器:</p><pre> class Chronometer { private: static int hour, min, sec; //std::stringstream ss; //Chronometer chrono; public: Chronometer(); static Chronometer& start_chrono(Chronometer& chrono); static Chronometer& finish_chrono(Chronometer& chrono); friend std::ostream& operator<<(std::ostream& flux, Chronometer t); Chronometer& operator=(const Chronometer& other); ~Chronometer(); };</pre><p> 對於線程,我嘗試了幾種參數。 最后一個:</p><pre> std::thread(&Chronometer::start_chrono, car_crono[i], std::ref(chrono));</pre><p> 我猜 ref 是必要的,但沒有改變。</p><p> 這是完整的錯誤</p><pre>/usr/include/c++/7/thread: In instantiation of 'struct std::thread::_Invoker<std::tuple<Chronometer& (*)(Chronometer&), Chronometer*, std::reference_wrapper<Chronometer> > >': /usr/include/c++/7/thread:127:22: required from 'std::thread::thread(_Callable&&, _Args&&...) [with _Callable = Chronometer& (*)(Chronometer&); _Args = {Chronometer*&, std::reference_wrapper<Chronometer>}]' recognizer_rtsp.cxx:348:76: required from here /usr/include/c++/7/thread:240:2: error: no matching function for call to 'std::thread::_Invoker<std::tuple<Chronometer& (*)(Chronometer&), Chronometer*, std::reference_wrapper<Chronometer> > >::_M_invoke(std::thread::_Invoker<std::tuple<Chronometer& (*)(Chronometer&), Chronometer*, std::reference_wrapper<Chronometer> > >::_Indices)' operator()() ^~~~~~~~ /usr/include/c++/7/thread:231:4: note: candidate: template<long unsigned int..._Ind> decltype (std::__invoke((_S_declval<_Ind>)()...)) std::thread::_Invoker<_Tuple>::_M_invoke(std::_Index_tuple<_Ind...>) [with long unsigned int..._Ind = {_Ind...}; _Tuple = std::tuple<Chronometer& (*)(Chronometer&), Chronometer*, std::reference_wrapper<Chronometer> >] _M_invoke(_Index_tuple<_Ind...>) ^~~~~~~~~ /usr/include/c++/7/thread:231:4: note: template argument deduction/substitution failed: /usr/include/c++/7/thread: In substitution of 'template<long unsigned int..._Ind> decltype (std::__invoke(_S_declval<_Ind>()...)) std::thread::_Invoker<std::tuple<Chronometer& (*)(Chronometer&), Chronometer*, std::reference_wrapper<Chronometer> > >::_M_invoke<_Ind...>(std::_Index_tuple<_Ind1...>) [with long unsigned int..._Ind = {0, 1, 2}]': /usr/include/c++/7/thread:240:2: required from 'struct std::thread::_Invoker<std::tuple<Chronometer& (*)(Chronometer&), Chronometer*, std::reference_wrapper<Chronometer> > >' /usr/include/c++/7/thread:127:22: required from 'std::thread::thread(_Callable&&, _Args&&...) [with _Callable = Chronometer& (*)(Chronometer&); _Args = {Chronometer*&, std::reference_wrapper<Chronometer>}]' recognizer_rtsp.cxx:348:76: required from here /usr/include/c++/7/thread:233:29: error: no matching function for call to '__invoke(std::__tuple_element_t<0, std::tuple<Chronometer& (*)(Chronometer&), Chronometer*, std::reference_wrapper<Chronometer> > >, std::__tuple_element_t<1, std::tuple<Chronometer& (*)(Chronometer&), Chronometer*, std::reference_wrapper<Chronometer> > >, std::__tuple_element_t<2, std::tuple<Chronometer& (*)(Chronometer&), Chronometer*, std::reference_wrapper<Chronometer> > >)' -> decltype(std::__invoke(_S_declval<_Ind>()...)) ~~~~~~~~~~~~~^~~~~~~~~~~~~~~~~~~~~~~ In file included from /usr/include/c++/7/tuple:41:0, from /usr/include/c++/7/bits/stl_map.h:63, from /usr/include/c++/7/map:61, from../alpr_utils.h:7, from recognizer_rtsp.cxx:34: /usr/include/c++/7/bits/invoke.h:89:5: note: candidate: template<class _Callable, class... _Args> constexpr typename std::__invoke_result<_Functor, _ArgTypes>::type std::__invoke(_Callable&&, _Args&&...) __invoke(_Callable&& __fn, _Args&&... __args) ^~~~~~~~ /usr/include/c++/7/bits/invoke.h:89:5: note: template argument deduction/substitution failed: /usr/include/c++/7/bits/invoke.h: In substitution of 'template<class _Callable, class... _Args> constexpr typename std::__invoke_result<_Functor, _ArgTypes>::type std::__invoke(_Callable&&, _Args&&...) [with _Callable = Chronometer& (*)(Chronometer&); _Args = {Chronometer*, std::reference_wrapper<Chronometer>}]': /usr/include/c++/7/thread:233:29: required by substitution of 'template<long unsigned int..._Ind> decltype (std::__invoke(_S_declval<_Ind>()...)) std::thread::_Invoker<std::tuple<Chronometer& (*)(Chronometer&), Chronometer*, std::reference_wrapper<Chronometer> > >::_M_invoke<_Ind...>(std::_Index_tuple<_Ind1...>) [with long unsigned int..._Ind = {0, 1, 2}]' /usr/include/c++/7/thread:240:2: required from 'struct std::thread::_Invoker<std::tuple<Chronometer& (*)(Chronometer&), Chronometer*, std::reference_wrapper<Chronometer> > >' /usr/include/c++/7/thread:127:22: required from 'std::thread::thread(_Callable&&, _Args&&...) [with _Callable = Chronometer& (*)(Chronometer&); _Args = {Chronometer*&, std::reference_wrapper<Chronometer>}]' recognizer_rtsp.cxx:348:76: required from here /usr/include/c++/7/bits/invoke.h:89:5: error: no type named 'type' in 'struct std::__invoke_result<Chronometer& (*)(Chronometer&), Chronometer*, std::reference_wrapper<Chronometer> >'</pre><p> 我應該通過線程傳遞什么樣的參數?</p><p> 我去了幾個鏈接來尋找解決方案,但沒有什么能解決我的問題:</p><p> <a href="https://stackoverflow.com/questions/21048906/stdthread-pass-by-reference-calls-copy-constructor" rel="nofollow noreferrer">std::thread 通過引用傳遞調用復制構造函數</a></p><p> <a href="https://stackoverflow.com/questions/67625058/no-matching-function-to-invoke-using-stdthread" rel="nofollow noreferrer">沒有匹配的 function 調用,使用 std::thread</a></p><p> ... </p></div></std::tuple<> 創建 std::functional object 來包裝 lambda 並調用 static 成員 function 包裝介紹性標准功能 在std :: function中包裝委托? C ++ 11 std :: thread給出錯誤:沒有匹配函數來調用std :: thread :: thread std線程調用模板成員函數模板類:編譯錯誤
 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM