Search code examples
c++stdreference-wrapper

Subscript operator for reference_wrapper


I recently learnt that std::reference_wrapper<T> has an overload for the the function call operator in case T is function-like. I wonder whether there is a reason given by the standard committee to not include an array subscript operator in cases where we capture something like std::vector. It seems weird to me that only one of the two typical operators which can be overloaded only as a class member are present in this standard class.

What is the rationale behind this?


Solution

  • In general, a reference wrapper cannot support every operation of the underlying type. For example, there's no way to automatically support the member functions. The subscript operator is just an ordinary operation, so there isn't a good reason to support it. Of course, we can get an operator[] that calls the underlying operator[], but then why not support operator+? operator==? How about begin and end? :)

    Overloading the function call operator has an important consequence, though: the class becomes a functor type. This can be useful for many situations. For example:

    std::for_each(first, last, std::ref(stateful_functor));
    

    This is a good reason for overloading operator().