C++ 参考手册

位置:首页 > C++ 参考手册 >工具库 >函数对象 >std::function > std::function<R(Args...)>::target

template< class T >
T* target() noexcept;
(1) (C++11 起)
template< class T >
const T* target() const noexcept;
(2) (C++11 起)

返回指向存储的可调用函数目标的指针。

参数

(无)

返回值

target_type() == typeid(T) 则为指向存储的函数的指针,否则为空指针。

示例

#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));
}

输出:

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

参阅

获得 std::function 所存储的目标的typeid
(公开成员函数)