簡體   English   中英

將參數傳遞給線程函數(模板化)

[英]Passing arguments to thread function (templated)

這個問題可能與為什么傳遞對象引用參數到線程函數無法編譯有關?

我遇到了類似的問題,但在我的情況下,仿函數是一個模板。

class A {
public:
  // Non template version works as expected!!.
  // void operator()(std::ostream& out){
  //    out << "hi\n";
  // }

  // template version doesn't. 
    template <class Ostream>
    void operator()(Ostream& out){
        out << "hi\n";
    }

};

int main() {
   A a;
   thread t(a, ref(cout));
   t.join();
}

GCC說:

error: no match for 'operator<<' in 'out << "hi\012"'

我怎么解決這個問題?

您正在傳遞std::reference_wrapper 所以class Ostream的類型將是std::reference_wrapper ,它解釋了錯誤。

template <class OstreamRef>
void operator()(OstreamRef& outRef){
    outRef.get()<< "hi\n";
}

這應該解決它。

對於非模板情況,當需要轉換為std::ostream&get()隱式調用get() 但是,使用模板不需要轉換為任何其他類型,因此std::reference_wrapper按原樣傳遞,因此需要顯式調用get() 謝謝@jogojapan

暫無
暫無

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

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