Quick Links: |
Provide copyable, assignable object wrapper for references. More...
bsl::reference_wrapper | class object to hold a reference to an object |
bsl::reference_wrapper
, a reduced implementation of the standard C++2011 template of the same name, which simply wraps a reference into a copyable, assignable object to allow it to be stored in a place that cannot normally hold a reference, such as a standard container. Because a reference wrapper is convertible to its contained reference type, it can be passed to functions that take such a reference. bsl::ref
and bsl::cref
that may be used to generate reference_wrapper
objects more concisely than with the constructor. struct Canary { static const int s_size = 1000; Canary *d_values[s_size]; Canary(); }; Canary::Canary() { for (int i = 0; i < s_size; ++i) { d_values[i] = this; } }
bool operator<(Canary const& a, Canary const& b) { return a.d_values[0] < b.d_values[0]; }
template <typename T> void sortTwoItems(T& a, T& b) { if (b < a) { T tmp(a); a = b; b = tmp; } }
sortTwoItems
on wrappers representing Canary
objects without need to move actual, large Canary
objects about. In the call to sortTwoItems
, below, the operator=
used in it is that of bsl::reference_wrapper<Canary>
, but the operator<
used is the one declared for Canary&
arguments. All of the conversions needed are applied implicitly: Canary canaries[2]; bsl::reference_wrapper<Canary> canaryA = bsl::ref(canaries[1]); bsl::reference_wrapper<Canary> canaryB = bsl::ref(canaries[0]); sortTwoItems(canaryA, canaryB); assert(&canaryA.get() == canaries); assert(&canaryB.get() == canaries + 1);