3

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

1
  • 2
    Basically, it forwards operator() to the referee Functor. Commented Jun 1, 2016 at 11:25

1 Answer 1

3

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.
Sign up to request clarification or add additional context in comments.

1 Comment

could you give an example for operator() of std::reference_wrapper

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.