Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't std::reference_wrapper implicitly cast to a reference when calling member function? [duplicate]

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<<)

like image 846
vsoftco Avatar asked Feb 05 '15 17:02

vsoftco


1 Answers

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.

like image 121
Mike Seymour Avatar answered Sep 30 '22 15:09

Mike Seymour