public member function
<functional>

std::reference_wrapper::operator()

template <class... ArgTypes>
  typename result_of<type&(ArgTypes&&...)>::type
    operator() (ArgTypes&&... args) const;
Access element (functional form)
Accesses the referred element.

The effect depends on the type referred by the reference_wrapper object (i.e., its class template parameter T, aliased as member type):

  • If type is a function or a function object type, it is called forwarding the arguments to the function.
  • If type is a pointer to a non-static member function, it is called using the first argument as the object on which the member is called (this may either be an object, a reference, or a pointer to it), and the remaining arguments are forwarded as arguments for the function.
  • If type is a pointer to a non-static data member, it should be called with a single argument, and the function returns a reference to that member of its argument (the argument may either be an object, a reference, or a pointer to it).

Parameters

args...
Arguments for the invocation.
If type is a member pointer, the first argument shall be an object for which that member is defined (or a reference, or a pointer to it).

Return value

If the function performs a function call, it returns the return value of that function.
Otherwise, it returns a reference to accessed member.

type is a member type describing the referred type (it is an alias of the class template parameter, T).

Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
// reference_wrapper::operator()
#include <iostream>     // std::cout
#include <functional>   // std::reference_wrapper, std::plus

struct AB {
  int a,b;
  int sum() {return a+b;}
};

 int ten() {return 10;}            // function

int main () {
  std::plus<int> plus_ints;        // function object
  int AB::* p_a = &AB::a;          // pointer to data member
  int(AB::* p_sum)() = &AB::sum;   // pointer to member function

  // construct reference_wrappers using std::ref:
  auto ref_ten = std::ref(ten);             // function
  auto ref_plus_ints = std::ref(plus_ints); // function object
  auto ref_AB_sum = std::ref(p_sum);        // pointer to member function
  auto ref_AB_a = std::ref(p_a);            // pointer to data member

  AB ab {100,200};

  // invocations:
  std::cout << ref_ten() << '\n';
  std::cout << ref_plus_ints(5,10) << '\n';
  std::cout << ref_AB_sum(ab) << '\n';
  std::cout << ref_AB_a( ab) << '\n';
  std::cout << ref_AB_a(&ab) << '\n';       // (also ok with pointer)

  return 0;
}


Output:
10
15
300
100
100

Data races

Both the object and its referred element are accessed.

Exception safety

Provides the same level as the element accessed.

See also