Second Helpings
The helper function
ref():
reference_wrapper<T> ref(T& t);
can be used as a short and convenient alternative to typing
reference_wrapper<int> (n):
//same as vi.push_back( reference_wrapper<int>(n));
vi.push_back(ref(n));
In places where a reference to a const object is needed, use the helper function
cref():
reference_wrapper<const T> cref(const T& t);
cref() takes a reference to a const object and returns a matching
reference_wrapper<const T> that provides an implicit conversion to const
T&. For example, you can use
cref() to create a
std::tr1::tuple object that stores references to
const:
#include <tuple>
#include<utility>
using std::tr1::tuple;
using std::tr1::make_tuple;
A a; const A ca = a;
tuple <const A&> cra(cref(ca));
make_tuple(ref(a)); // tuple <A&>
tuple <A> t(a);
Author's Note: Technically speaking, const T& is a (non-const) reference to const T, not a const reference to T (C++ doesn't have const references anyway). However, the term "const reference" is used frequently in the C++ literature to denote "reference to const". |
Similarly, a reference wrapper can be used with the std::tr1::function facility to create references to function objects and references to const function objects:
class Data
{
private:
vector <pair<int, int> > records;
public:
bool operator()(int x, int y)
{
records.push_back(make_pair(x, y));
return x < y;
}
};
Data rec;
function <bool(int, int)> func = ref(rec);
Wrap up
The reference wrapper library is a small, but valuable, enhancement to standard C++. Several other TR1 components, like
tuples and
std::tr1::function, depend on it. As you have seen, this small library has useful applications in everyday C++ programming as well.