简体   繁体   English

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

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

I'd like to use the std::reference_wrapper<T>::operator() "the same" as std::reference_wrapper<T>::get , but following example fails for 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;
}

Is this possible?这可能吗? Where is my misunderstanding?我的误解在哪里?

Thanks for the help谢谢您的帮助

Zlatan兹拉坦

operator() of std::reference_wrapper does not do the same as .get() . std::reference_wrapperoperator().get()不同。

Its operator() invokes a function or other Callable object to which the stored reference refers.它的operator()调用存储引用所引用的 function 或其他Callable object。

In your example a Foo object is not a Callable .在您的示例中, Foo object 不是Callable If Print was instead operator() , then you could simply call it with如果Print改为operator() ,那么您可以简单地调用它

wrapper();

Is this possible?这可能吗? Where is my misunderstanding?我的误解在哪里?

No. std::reference_wrapper<T>::operator() only exists when T::operator() exists, and it simply calls that, forwarding the arguments provided.没有。 std::reference_wrapper<T>::operator()仅在T::operator()存在时才存在,它只是调用它,转发提供的 arguments。

Are you mistaking it for std::reference_wrapper<T>::operator T& ?您是否将其误认为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