簡體   English   中英

如何使用 std::reference_wrapper<t> ::操作員()</t>

[英]How to use std::reference_wrapper<T>::operator()

我想使用與std::reference_wrapper<T>::operator() std::reference_wrapper<T>::get operator() ,但以下示例對於operator()失敗

#include <cstdint>
#include <functional>

class Foo {
public:
  void Print() {
    std::printf("Foo\n");
  }
};

class Bar {
public:
  Bar(Foo &foo): wrapper{foo} {}
  void Print() {
    wrapper.get().Print();  // OK
    // wrapper().Print();   // FAIL
  }
private:
  std::reference_wrapper<Foo> wrapper;
};

int main() {
  Foo foo{};
  Bar bar{foo};
  bar.Print();
  return 0;
}

這可能嗎? 我的誤解在哪里?

謝謝您的幫助

茲拉坦

std::reference_wrapperoperator().get()不同。

它的operator()調用存儲引用所引用的 function 或其他Callable object。

在您的示例中, Foo object 不是Callable 如果Print改為operator() ,那么您可以簡單地調用它

wrapper();

這可能嗎? 我的誤解在哪里?

沒有。 std::reference_wrapper<T>::operator()僅在T::operator()存在時才存在,它只是調用它,轉發提供的 arguments。

您是否將其誤認為std::reference_wrapper<T>::operator T&

class Bar {
public:
  Bar(Foo &foo): wrapper{foo} {}
  void Print() {
    Foo & f = wrapper;
    f.Print()
  }
private:
  std::reference_wrapper<Foo> wrapper;
};

暫無
暫無

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

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