C++11 std::function

@time    2019-07-07
@author  Ruo_Xiao

1、头文件

#include <functional>

2、作用

        类模版 std::function 是一种通用、多态的函数封装,形成一个新的可调用的 std::function 对象。std::function 的实例可以对任何可以调用对象进行存储复制调用操作。std::function 对象是对 C++ 中现有的可调用实体的一种类型安全的包裹(我们知道像函数指针这类可调用实体,是类型不安全的),就是函数的容器。当我们有了函数的容器之后便能够更加方便的将函数、函数指针作为对象进行处理。

        关于可调用对象的概念:对于一个对象或表达式,如果可以对其使用调用运算符,则称该对象或表达式为可调用对象。

        可调用对象包括:

        (1)函数

        (2)函数指针

        (3)lambda 表达式

        (4)bind 创建的对象

        (5)重载了函数调用运算符的类(仿函数)。

3、std::function 的使用有多态和万总归一的感觉,程序栗子如下:

#include <functional>
#include <iostream>

std::function<void(std::string)> Functional;

// 普通函数。
void TestFunc(std::string str)
{
    std::cout << str << std::endl;
}

// Lambda表达式。
auto lambda = [](std::string str) -> void { std::cout << str << std::endl; };

// 仿函数(functor)。
class Functor
{
public:
    void operator()(std::string str)
    {
        std::cout << str << std::endl;
    }
};

// 1.类成员函数。
// 2.类静态函数。
class TestClass
{
public:
    void ClassMember(std::string str)
    {
        std::cout << str << std::endl;
    }
    static void StaticMember(std::string str)
    {
        std::cout << str << std::endl;
    }
};

int main()
{
    // 普通函数。
    Functional = TestFunc;
    Functional("普通函数");

    // Lambda表达式。
    Functional = lambda;
    Functional("Lambda 表达式");

    // 仿函数。
    Functor testFunctor;
    Functional = testFunctor;
    Functional("仿函数");

    // 类成员函数。
    TestClass testObj;
    Functional = std::bind(&TestClass::ClassMember, testObj, std::placeholders::_1);
    Functional("类成员函数");

    // 类静态函数。
    Functional = TestClass::StaticMember;
    Functional("类静态函数");

    return 0;
}

结果:

普通函数
Lambda 表达式
仿函数
类成员函数
类静态函数

(SAW:Game Over!)

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值