[ reference_wrapper ]

A C++ reference cannot be copied. The reference_wrapper is class template that acts as a reference whose instances can be copied.

Explicit constructor:

#include <tr1/functional>
using std::tr1::reference_wrapper;

explicit reference_wrapper::reference_wrapper(Ty &obj);

example:

           
template<typename T>
struct wrap
{
    reference_wrapper<T> _M_ref;

    wrap(T &e)
    : _M_ref(e)
    {}
};

...

int i, j;
        
wrap<int> w(i);
wrap<int> q(j);
    
w = q;  // the reference_wrapper can be copied, therefore the wrap instances can be copied too
 

Member function get() and operator Ty&()

the member function get() returns a reference to Ty:

Ty& get() const;

the operator Ty&() allows implicit conversions to Ty:

operator Ty&() const;

note: if Ty is a callable type, the reference_wrapper is a call wrapper and the call operator() can be used to call the object it refers to.

cref, ref template functions:

the reference_wrapper can be created indirectly by means of the following template functions:

template <class Ty>
reference_wrapper<const Ty> cref(const Ty &obj);

template <class Ty>
reference_wrapper<const Ty> cref(reference_wrapper<Ty> obj);

template <class Ty>
reference_wrapper<Ty> ref(const & obj);

template <class Ty>
reference_wrapper<Ty> ref(reference_wrapper<Ty> obj);

Nested Types

the nested type refers to Ty:

typedef Ty reference_wrapper::type;

the reference_wrapper<Ty> is derived from std::unary_function<T1, Ret>  if:
  • Ty is a function type or pointer to a function type taking one argument of type T1 and returning Ret;
  • Ty is a pointer to member function that takes no arguments; T1 is the cv qualified version of Ty* and Ret is the return type;
  • Ty is a type derived from std::unary_function<T1,Ret>; 
then:

the nested typedef result_type refers to Ret: 

typedef Ret reference_wrapper::result_type;

the nested typedef argument_type refers to T1:

typedef T1 reference_wrapper::argument_type;


the reference_wrapper<Ty> is derived from std::binary_function<T1, T2, Ret> if:
  • Ty is a function type or pointer to function type that takes two arguments: T1 and T2 and returning Ret;
  • Ty is a pointer to member function that take one argument of type T2; T1 is the cv qualified version of Ty* and Ret is the return type;
  • Ty is a type derived from std::binary_function<T1, T2, Ret>;
then:

the nested typedef result_type refers to Ret: 

typedef Ret reference_wrapper::result_type;

the nested typedef first_argument_type refers to T1, the second_argument_type refers to T2:

typedef T1 reference_wrapper::first_argument_type;
typedef T2 reference_wrapper::second_argument_type;


Comments