C++11特性值std::function

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

关于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<iostream>
#include<functional>

using namespace std;

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

template <class T> T g_Add(T i, T j)
{
    cout<< i + j<<endl;
    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<class T>
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<class T>
    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<void()> f1 = gFunc;
    f1();
    
    std::function<int(int, int)> f2 = g_Add<int>;
    cout<<f2(2, 3)<<endl;
    
    std::function<int(int, int)> f3 = g_Lambda;
    cout<<f3(4,6)<<endl;
    
    std::function<int(int, int)> f4 = Add();
    cout<<f4(8, 9)<<endl;
    
    std::function<int(int, int)> ft = AddT<int>();
    cout<<ft(5, 6)<<endl;
    
    std::function<int(int, int)> f5 = &Computer::Add;
    cout<< f5 (1, 2) <<endl;
    
    std::function<int (int, int)> ftStatic  = &Computer::AddT<int>;
    cout<<ftStatic(2, 3)<<endl;
    
    Computer c;
    
    std::function<int(int, int)> fN = std::bind(&Computer::AddN, &c, placeholders::_1, placeholders::_2);
    cout<< fN(1, 1) << endl;

    return 0;
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值