public member function
<functional>

std::function::target_type

const type_info& target_type() const noexcept;
Target type_info
Returns the type_info object that identifies the type of the target.

The function returns the same as applying the typeid operator to the type of the callable object used as target.

If the object has no target (i.e., it is an empty function), this function returns typeid(void).

Note that a single type instantiation of function is able to hold different target types with the same calling signatures: for example, the same function object may hold a pointer to a function or a function object.

Parameters

none

Return value

The type_info object that corresponds to the type of the target, or typeid(void) if the object is an empty function.

type_info is a type defined in header <typeinfo> that can be used to compare types.

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

int  plus_function(int a, int b) {return a+b;}
int minus_function(int a, int b) {return a-b;}

int main () {
  std::function<int(int,int)> plus1  = plus_function;
  std::function<int(int,int)> plus2  = std::plus<int>();
  std::function<int(int,int)> minus1 = minus_function;
  std::function<int(int,int)> minus2 = std::minus<int>();

  std::cout << "pointers as targets:\n" << std::boolalpha;
  std::cout << "plus1 : " << ( plus1.target_type()==typeid(int(*)(int,int))) << '\n';
  std::cout << "plus2 : " << ( plus2.target_type()==typeid(int(*)(int,int))) << '\n';
  std::cout << "minus1: " << (minus1.target_type()==typeid(int(*)(int,int))) << '\n';
  std::cout << "minus2: " << (minus2.target_type()==typeid(int(*)(int,int))) << '\n';
  std::cout << '\n';

  std::cout << "same type?:\n";
  std::cout << "(plus1, plus2) : " << ( plus1.target_type()== plus2.target_type()) << '\n';
  std::cout << "(minus1,minus2): " << (minus1.target_type()==minus2.target_type()) << '\n';
  std::cout << "(plus1, minus1): " << ( plus1.target_type()==minus1.target_type()) << '\n';
  std::cout << "(plus2, minus2): " << ( plus2.target_type()==minus2.target_type()) << '\n';

  return 0;
}

Output:
pointers as targets:
plus1 : true
plus2 : false
minus1: true
minus2: false

same type?:
(plus1, plus2) : false
(minus1,minus2): false
(plus1, minus1): true
(plus2, minus2): false


Data races

The object is accessed.

Exception safety

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

See also