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()
#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
CodePudding user response:
operator()
of std::reference_wrapper
does not do the same as .get()
.
Its operator()
invokes a function or other Callable object to which the stored reference refers.
In your example a Foo
object is not a Callable. If Print
was instead operator()
, then you could simply call it with
wrapper();
CodePudding user response:
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.
Are you mistaking it for 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;
};