Quick Links:

bal | bbl | bdl | bsl

Component bslstl_referencewrapper
[Package bslstl]

Provide copyable, assignable object wrapper for references. More...

Outline
Purpose:
Provide copyable, assignable object wrapper for references.
Classes:
bsl::reference_wrapper class object to hold a reference to an object
Canonical Header:
bsl_functional.h
Description:
This component provides 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.
This component also provides the (free) helper functions bsl::ref and bsl::cref that may be used to generate reference_wrapper objects more concisely than with the constructor.
NOTE: This component is a partial implementation of the standard class, omitting support for use as a function object, and is in any case of limited usefulness in a pure C++98 environment.
Usage:
This section illustrates intended use of this component.
Example 1: Sorted References:
Let us suppose that we wish to handle objects that will be passed to a comparison function expecting references to the objects. Let us suppose further that these objects are large enough that we would not wish to move them around bodily as they are sorted. Note that plausible examples of uses for this component are limited in freestanding C++98.
First, let us define the large-object type:
  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;
       }
  }
Next, we define the comparison function:
  bool operator<(Canary const& a, Canary const& b)
  {
      return a.d_values[0] < b.d_values[0];
  }
Finally, we define a generic function to sort two items:
  template <typename T>
  void sortTwoItems(T& a, T& b)
  {
      if (b < a) {
          T tmp(a);
          a = b;
          b = tmp;
      }
  }
We can call 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);