Search code examples
c++referencereference-wrapper

Implementation of std::reference_wrapper


While looking at the implementation of std::reference_wrapper here

The constructors and operators are obvious to me but I didn't understand this part

template< class... ArgTypes >
typename std::result_of<T&(ArgTypes&&...)>::type
  operator() ( ArgTypes&&... args ) const {
  return std::invoke(get(), std::forward<ArgTypes>(args)...);
}

Could someone simplify it for me ... would be appreciated

Edit: and would be great to give useful example for operator() of std::reference_wrapper


Solution

  • This defines the operator() member function, which is applicable for an std::reference_wrapper wrapping a reference to a Callable. The purpose of it is to call the underlying Callable.

    • The template parameter class ... Args is to make it generic in terms of the parameters that can be passed to the underlying Callable.
    • The return type of the operator has to be the return type produced by invoking the Callable, which is obtained by the typename std::result_of<T&(ArgTypes&&...)>::type part
    • It uses the invoke call as a general-purpose way of calling the Callable, which works irrespective of what type of Callable it is (Functor, function pointer, member function pointer etc).
    • It uses std::forward in passing the argument list to achieve perfect forwarding - so for example lvalue and rvalues passed in to the original call retain their l/rvalue-ness in the underlying call.