每日 C++ - std::function

std::function 与函数指针

std::function 可以代替函数指针

bool IsEmpty(const std::string& str)
{
    return str.empty();
}
typedef bool (*pIsEmpty)(cosnt std::string& str);
using is_empty = std::function<bool(const std::string& str)>;
int main()
{
    std::string str("Hello");
    is_empty f = IsEmpty;
    std::cout << str << " is empty :" << f(str) << std::endl;

    pIsEmpty pf = &IsEmpty;
    std::cout << str << " is empty :" << pf(str) << std::endl;
    return 0;
}

打印

Hello is empty :0
Hello is empty :0

std::function 与 Functor

Functor 是一种类函数化的方式

定义一个 Functor

class IsEmpty_Class {
public:
    bool operator()(const std::string& str)
    {
        return str.empty();
    }
};
using is_empty = std::function<bool(const std::string& str)>;
int main()
{
    std::string str("Hello");
    IsEmpty_Class c;
    is_empty f = c;
    std::cout << str << " is empty :" << c(str) << std::endl;
    std::cout << str << " is empty :" << f(str) << std::endl;
    return 0;
}

打印

Hello is empty :0
Hello is empty :0

std::function 与 lambda

lambda 是 C++11 的新特性,为了连贯,我们定义一个 lambda

// lambda
auto IsEmpty_Lambda = 
    [](const std::string& str) 
    -> bool { 
        return str.empty(); 
    };
using is_empty = std::function<bool(const std::string& str)>;
int main()
{
    std::string str("Hello");
    is_empty f = IsEmpty_Lambda;
    std::cout << str << " is empty :" << f(str) << std::endl;
    std::cout << str << " is empty :" << IsEmpty_Lambda(str) << std::endl;
    return 0;
}

打印

Hello is empty :0
Hello is empty :0

std::function 延迟绑定

std::bind 绑定调用对象和对象参数,绑定后的结果可以使用 std::function 进行保存,类似一个委托对象。

class IsEmpty_Class_Member {
public:
    bool isEmpty(const std::string& str)
    {
        return str.empty();
    }
   
    std::string str = "Hello";
};

int main()
{
    IsEmpty_Class_Member cm;
    is_empty f = std::bind(&IsEmpty_Class_Member::isEmpty, &cm, std::placeholders::_1);
    std::cout << str << " is empty :" << f(str) << std::endl;
    std::function<std::string&(void)> cmf_str = std::bind(&IsEmpty_Class_Member::str, &cm);
    cmf_str() = "Hello Wolrd";  // 由于绑定 cm 引用,可以外部更改 cm 值
    std::cout << "IsEmpty_Class_Member str :" << cm.str << std::endl;
    return 0;
}

打印

Hello is empty :0
IsEmpty_Class_Member str :Hello Wolrd
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值