std::function::target

From cppreference.com
< cpp‎ | utility‎ | functional‎ | function
 
 
 
Function objects
Function wrappers
(C++11)
(C++11)
Bind
(C++11)
(C++11)
(C++11)
Reference wrappers
(C++11)(C++11)
Operator wrappers
Negators
Deprecated binders and adaptors
(deprecated)
(deprecated)
(deprecated)
(deprecated)
(deprecated)(deprecated)(deprecated)(deprecated)
(deprecated)
(deprecated)(deprecated)(deprecated)(deprecated)
(deprecated)(deprecated)
(deprecated)(deprecated)
 
 
template< class T >
T* target();
(1) (since C++11)
template< class T >
const T* target() const;
(2) (since C++11)

Returns a pointer to the stored callable function target.

Contents

[edit] Parameters

(none)

[edit] Return value

A pointer to the stored function if target_type() == typeid(T), otherwise a null pointer.

[edit] Exceptions

noexcept specification:  
noexcept
  

[edit] Example

#include <functional>
#include <iostream>
 
int f(int, int) { return 1; }
int g(int, int) { return 2; }
void test(std::function<int(int, int)> const& arg)
{
    std::cout << "test function: ";
    if (arg.target<std::plus<int>>())
        std::cout << "it is plus\n";
    if (arg.target<std::minus<int>>())
        std::cout << "it is minus\n";
 
    int (*const* ptr)(int, int) = arg.target<int(*)(int, int)>();
    if (ptr && *ptr == f)
        std::cout << "it is the function f\n";
    if (ptr && *ptr == g)
        std::cout << "it is the function g\n";
}
 
int main()
{
    test(std::function<int(int, int)>(std::plus<int>()));
    test(std::function<int(int, int)>(std::minus<int>()));
    test(std::function<int(int, int)>(f));
    test(std::function<int(int, int)>(g));
}

Output:

test function: it is plus
test function: it is minus
test function: it is the function f
test function: it is the function g

[edit] See also

obtains the typeid of the stored target of a std::function
(public member function)