std::invoke解析

初识std::invoke

        std::invoke是c++17标准库引入的一个函数模板。这个函数模板能做什么?原理是什么?先来看一个简单的例子,回答std::invoke“能做什么”。

#include <functional>
#include <iostream>
#include <algorithm>
#include <vector>

int add(int a, int b) { return a + b; }
int sub(int a, int b) { return a - b; }

struct calc {
    int add(int a, int b) { return a + b; }
    int sub(int a, int b) { return a - b; }
};

int main(int argc, char **argv)
{
    int _add = std::invoke(add, 4, 5);
    int _sub = std::invoke(sub, 7, 3);
    calc cobj;
    _add = std::invoke(&calc::add, cobj, 40, 5);
    _sub = std::invoke(&calc::sub, cobj, 70, 3);
    
    return 0;
}

        通过上面的例子,可以看出,std::invoke仅仅是对函数指针的调用做了一下封装,这种技术被称作委托。单从上面的例子来看,std::invoke的存在没有任何意义:直接调用函数更加方便,效率也更高,而通过std::invoke调用并不能带来任何收益。再来看一个例子:

#include <functional>
#include <iostream>
#include <algorithm>

template <typename T>
class rectangle {
public:
    rectangle(void) {}
    
    T area_for_rectangle(T a, T b) { return a * b; }
};

template <typename T>
class circular {
public:
    circular(void) {}
    T area_for_circular(T r) { return 3.1
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值