繁体   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