【C++11】类型安全与std::function

1.类型安全

类型安全概念的链接

引用阅读1

2.std::function

引用阅读2

std::function的实例可以对任何能够调用的目标实体进行封装调用,这些目标实体包括普通函数、lambda
表达式、函数指针、仿函数、类的普通成员函数和类的静态成员函数等。std::function对象是对C++中现
有的可调用实体的一种类型安全的封装(我们知道像函数指针这类可调用实体是类型不安全的),示例代
码如下:

#include <functional>
#include <iostream>
using namespace std;
 
std::function<int(int)> func;
 
// 普通函数
int testFunc(int a)
{
    return a;
}
 
// lambda表达式
auto lambda = [](int a)->int{ return a; };
 
// 仿函数(实现operator()的函数)
class Functor
{
public:
    int operator()(int a)
    {
        return a;
    }
};
 
// 类的普通成员函数和静态成员函数
class TestClass
{
public:
    int ClassMember(int a) { return a; }
    static int StaticMember(int a) { return a; }
};
 
int main()
{
    // 普通函数
    func = testFunc;
    int result = func(10);
    cout << "普通函数:"<< result << endl;
 
    // lambda表达式
    func = lambda;
    result = func(20);
    cout << "lambda表达式:"<< result << endl;
 
    // 仿函数
    Functor testFunctor;
    func = testFunctor;
    result = func(30);
    cout << "仿函数:"<< result << endl;
 
    // 类的普通成员函数
    TestClass testObj;
    func = std::bind(&TestClass::ClassMember, &testObj, std::placeholders::_1);
    result = func(40);
    cout << "类的普通成员函数:"<< result << endl;
 
    // 类的静态成员函数
    func = TestClass::StaticMember;
    result = func(50);
    cout << "类的静态成员函数:"<< result << endl;
 
    return 0;
}

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值