I don't understand exactly why one cannot use a std::reference_wrapper
like this:
#include <vector>
#include <functional>
struct Foo
{
void f() {};
};
int main()
{
std::vector<std::reference_wrapper<Foo>> vrFoo;
Foo foo;
vrFoo.push_back(foo);
// vrFoo[0].f(); // error
vrFoo[0].get().f(); // or static_cast<Foo&>(v[0]).f();
}
Why do we have to use the get()
member function? It looks like std::reference_wrapper
has an implicit conversion to T&
via operator T&() const noexcept
, see http://en.cppreference.com/w/cpp/utility/functional/reference_wrapper
so why isn't v[0]
implicitly converted to a reference?
In other situations, such as
std::cout << v[0] << std::endl
this conversion takes place (I assume here that Foo
overloads operator<<
)
Because .
is always used to access members of the object it's applied to. Type conversions aren't considered.
There's a proposal to allow overloading of operator.
, to enable exactly what you want, but that won't be standard until at least C++17, if at all.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With