public member function
<functional>

std::function::target

template <class TargetType>       TargetType* target() noexcept;template <class TargetType> const TargetType* target() const noexcept;
Get pointer to target
Returns a pointer to the callable object stored in the function object.

Because function is a polymorphic wrapper class, it is unaware of the static type of its target callable object, and thus the template parameter TargetType must be explicitly specified.

TargetType shall match the target type, so that typeid(TargetType)==target_type(). Otherwise, the function always returns a null pointer.

Parameters

none

Return value

A pointer to the target callable object, if typeid(TargetType) compares equal to the value returned by member target_type.
Otherwise, a null pointer.

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
// function::target example
#include <iostream>     // std::cout, std::boolalpha
#include <functional>   // std::function, std::plus, std::minus

int my_plus (int a, int b) {return a+b;}
int my_minus (int a, int b) {return a-b;}

int main () {
  std::function<int(int,int)> foo = my_plus;
  std::function<int(int,int)> bar = std::plus<int>();

  // calling using functional form:
  std::cout << foo(100,20) << '\n';
  std::cout << bar(100,20) << '\n';

  // calling by invoking target:
  std::cout << (*foo.target<int(*)(int,int)>())(100,20) << '\n';
  std::cout << (*bar.target<std::plus<int>>())(100,20) << '\n';

  // changing target directly:
  *foo.target<int(*)(int,int)>() = &my_minus;
  std::cout << foo(100,20) << '\n';

  return 0;
}

Output:
120
120
120
120
80


Data races

Both the object and its target are accessed.
The pointer returned can be used to access or modify the target callable object.

Exception safety

No-throw guarantee: this member function never throws exceptions.

See also