C++11 std::function(5种可调用对象)-GCC 4.9编译通过

类模版std::function是一种通用、多态的函数封装,形成一个新的可调用的std::function对象。std::function的实例可以对任何可以调用对象进行存储、复制和调用操作。std::function对象是对C++中现有的可调用实体的一种类型安全的包裹(我们知道像函数指针这类可调用实体,是类型不安全的)。
关于可调用对象的概念:对于一个对象或表达式,如果可以对其使用调用运算符,则称该对象或表达式为可调用对象。
可调用对象包括:
(1)函数。
(2)函数指针。
(3)lambda 表达式。
(4)bind 创建的对象。
(5)重载了函数调用运算符的类(仿函数)。

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

Output:

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

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值