Search code examples
c++11ref

Why is this simplest C++0x code not valid?


I encountered a weird problem just now.

The source code is simple and self-evident as follows:

#include <vector>
#include <iostream>
#include <functional>

using namespace std;
using namespace std::tr1;

template<class T_>
void show_size(T_ coll)
{   
    cout << coll.size();
}

int main()
{
    vector<int> coll;
    coll.push_back(1);

    show_size(ref(coll));

    return 0;
}

The VC++ 2010 reports:

error C2039: 'size' : is not a member of 'std::tr1::reference_wrapper<_Ty>'

As we know, reference_wrapper can automatically convert itself to its underlying type, here is vector<int>. Why is such simple code not valid?


Solution

  • No it can't that's the whole point of the reference wrapper, because it doesn't decay from the reference, unless explicitly requested using .get()

    Edit: don't mix up the boosts reference wrapper with the standard one, the boost one actually has implicit conversion (but the target functionality is a little bit different)