![](/img/trans.png)
[英]How can std::reference_wrapper<int> use operator+= if std::reference_wrapper doesn't have operator+=?
[英]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_wrapper
的operator()
与.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.