C++11特性值std::function

std::function是C++11添加的新特性之一,需要使用头文件 #include

关于std::function官方说明如下:

Class template std::function is a general-purpose polymorphic function wrapper. Instances of std::function can store, copy, and invoke any Callable target -- functions, lambda expressions, bind expressions, or other function objects, as well as pointers to member functions and pointers to data members.

The stored callable object is called the target of std::function. If a std::function contains no target, it is called empty. Invoking the target of an empty std::function results in std::bad_function_call exception being thrown.

std::function satisfies the requirements of CopyConstructible and CopyAssignable.

std::function是一种通用的函数包装器。模板本身,可以支持多种类型,该特性也被有的计算机从业者称为多态性。std::function可以存储、赋值和调用任何Callable目标的实例————函数、lambda表达式,绑定表达式或其他函数对象,以及成员函数和指向数据成员的指针。

样例如下:

#include
#include

using namespace std;

void gFunc() 
{
    cout<<"gFunc"< }

template T g_Add(T i, T j)
{
    cout<< i + j<     return i + j;
}

auto g_Lambda = [](int i, int j)
{
    return i + j;
};

struct Add
{
    int operator()(int i, int j)
    {
        return i + j;
    }
};

template
struct AddT
{
    T operator()(T i, T j)
    {
        return i + j;
    }
};

class Computer
{
public:
    static int Add(int i, int j)
    {
        return i + j;
    }        
    
    template
    static T AddT(T i, T j)
    {
        return i + j;
    }
    
    int AddN(int i, int j)
    {
        return i + j;
    }
};

int main(int argc, char **argv) 
{
    std::function f1 = gFunc;
    f1();
    
    std::function f2 = g_Add;
    cout<     
    std::function f3 = g_Lambda;
    cout<     
    std::function f4 = Add();
    cout<     
    std::function ft = AddT();
    cout<     
    std::function f5 = &Computer::Add;
    cout<< f5 (1, 2) <     
    std::function ftStatic  = &Computer::AddT;
    cout<     
    Computer c;
    
    std::function fN = std::bind(&Computer::AddN, &c, placeholders::_1, placeholders::_2);
    cout<< fN(1, 1) << endl;

    return 0;
}

你可能感兴趣的:(C++)