Login | Register   
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


advertisement
 

Solve the Forwarding Problem and Simulate Containers of References-3 : Page 3


advertisement
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.



Danny Kalev is a certified system analyst and software engineer specializing in C++. He was a member of the C++ standards committee between 1997 and 2000 and has since been involved informally in the C++0x standardization process. He is the author of "The ANSI/ISO Professional C++ Programmer's Handbook" and "The Informit C++ Reference Guide: Techniques, Insight, and Practical Advice on C++."
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap