C++14:std::bind和std::function

本文通过多个实例详细介绍了如何在C++中使用std::function和std::bind来创建仿函数和实现延迟调用。包括绑定类成员函数、成员变量以及不同类型的函数对象。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

知道std::bind和std::function,绑定函数,利用std::function形成仿函数,进行延时调用,这里是我记录下来两个demo方便自己理解的。

1

#include "stdafx.h"
#include <iostream>
#include <iomanip>//主要是对cin,cout之类的一些操纵运算子,比如setfill,setw,setbase,setprecision等等。它是I/O流控制头文件,就像C里面的格式化输出一样
#include <memory>
#include <functional>

typedef   std::function<void(int)>   HandlerEvent;

//定义一个成员变量
class Sharp
{
public:
    HandlerEvent handlerEvent;
};
//设置handlerEvent的值来动态装载事件响应函数
class Rectangle
{
private:
    std::string name;
    Sharp sharp;
public:
    void initial(void);
    const Sharp getSharp() const;
    static    //static一定要有
    void onEvent(int param)
    {
        std::cout << "invode onEvent method,get parameter: " << param << std::endl;
    }
};
//类的实现方法
void Rectangle::initial()
{
    sharp.handlerEvent = HandlerEvent(&Rectangle::onEvent);   
    //sharp.handlerEvent = std::bind(&Rectangle::onEvent,this,std::placeholders::_1);
    std::cout << "invode initial function!" << std::endl;
}
const Sharp Rectangle::getSharp() const
{
    return sharp;
}

//测试函数
int main(int argc, char *argv[]){
    std::cout << "hi: " << std::setw(50) << "hello world!" << std::endl;
    Rectangle rectangle;
    rectangle.initial();
    rectangle.getSharp().handlerEvent(23);   //返回一个Sharp对象
    std::cin.get();
}
//输出结果
/*hi:                                       hello world!
invode initial function!
invode onEvent method, get parameter : 23*/

使用std::function调用类成员函数一定是静态的,否错出现下面的错误:

这里写图片描述
如果使用std::bind就不需要static了(注释掉的那一行)。

2

#include "stdafx.h"
#include <iostream>
#include <iomanip>
#include <memory>
#include <functional>

typedef   std::function<void(int)>   HandlerEvent;

//定义一个成员变量
class Sharp
{
public:
    HandlerEvent handlerEvent;
};
//设置handlerEvent的值来动态装载事件响应函数
class Rectangle
{
private:
    std::string name;
    Sharp sharp;
public:
    void initial(void);
    const Sharp getSharp() const;
    virtual void onEvent(int param)
    {
        std::cout << "invode Rectangle's onEvent method,get parameter: " << param << std::endl;
    }
};
//Square类来继承Rectangle类,并重写onEvent
class Square : public Rectangle{
public:
    void onEvent(int param)
    {
        std::cout << "invode Square's onEvent method,get parameter: " << param << std::endl;
    }
};

//类的实现方法
void Rectangle::initial()
{
    sharp.handlerEvent = std::bind(&Rectangle::onEvent, this, std::placeholders::_1);
    std::cout << "invode initial function!" << std::endl;
}
const Sharp Rectangle::getSharp() const
{
    return sharp;
}

//测试函数
int main(int argc, char *argv[]){
    std::cout << "hi: " << std::setw(50) << "hello world!" << std::endl;

    Rectangle rectangle;
    rectangle.initial();
    rectangle.getSharp().handlerEvent(23);

    Square square;
    square.initial();
    square.getSharp().handlerEvent(33);

    std::cin.get();
}
//输出结果
/*hi:                                       hello world!
invode initial function!
invode Rectangle's onEvent method,get parameter: 23
invode initial function!
invode Square's onEvent method,get parameter: 33*/

这个例子在实际应用中,接口写成纯虚函数最好!体现了延迟调用。

3

#include "stdafx.h"
#include<iostream>// std::cout
#include<functional>// std::function

class A
{
public:
    int i_ = 0; // C++11允许非静态(non-static)数据成员在其声明处(在其所属类内部)进行初始化

    void output(int x, int y)
    {
        std::cout << x << "" << y << std::endl;
    }

};

int main()
{
    A a;
    // 绑定成员函数,保存为仿函数
    std::function<void(int, int)> fr = std::bind(&A::output, &a, std::placeholders::_1, std::placeholders::_2);
    // 调用成员函数
    fr(1, 2);

    // 绑定成员变量
    std::function<int&(void)> fr2 = std::bind(&A::i_, &a);
    fr2() = 100;// 对成员变量进行赋值
    std::cout << a.i_ << std::endl;
    return 0;
}

4

总结:

#include "stdafx.h"
#include <functional>
#include <iostream>
using namespace std;

std::function< int(int)> Functional;

// 普通函数
int TestFunc(int a)
{
    return a;
}

// Lambda表达式
auto lambda = [](int a)->int{ return a; };

// 仿函数(functor)
class Functor
{
public:
    int operator()(int a)
    {
        return a;
    }

    static int lala(int a) 
    {
        return a;
    }
};

// 1.类成员函数
// 2.类静态函数
class TestClass
{
public:
    int ClassMember(int a) { return a; }
    static int StaticMember(int a) { return a; }
};

int main()
{
    // 普通函数
    Functional = TestFunc;
    int result = Functional(10);
    cout << "普通函数:" << result << endl;

    // Lambda表达式
    Functional = lambda;
    result = Functional(20);
    cout << "Lambda表达式:" << result << endl;

    // 仿函数
    //Functor testFunctor;
    Functional = &Functor::lala;
    result = Functional(30);
    cout << "仿函数:" << result << endl;

    // 类成员函数
    TestClass testObj;
    Functional = std::bind(&TestClass::ClassMember, testObj, std::placeholders::_1);
    result = Functional(40);
    cout << "类成员函数:" << result << endl;

    // 类静态函数
    Functional = TestClass::StaticMember;
    result = Functional(50);
    cout << "类静态函数:" << result << endl;
    system("PAUSE");
    return 0;
}

5、

#include <iostream>
#include <functional>

void call_when_event(int x, const std::function<void(int)>& f)
{
    if (!(x & 1))
    {
        f(x);
    }
}

void output(int x)
{
    std::cout << x <<std:: endl;
}

void output2(int x)
{
    std::cout << x + 2 << std::endl;
}

int main()
{
    {
        auto ft = std::bind(output, std::placeholders::_1);
        for (int i = 0; i < 10; i++)
        {
            call_when_event(i, ft);
        }
        std::cout << "第一个完了" << std::endl;
    }
    {
        auto ft2 = std::bind(output2, std::placeholders::_1);
        for (int i = 0; i < 10; i++)
        {
            call_when_event(i, ft2);
        }
        std::cout << "第二个完了" << std::endl;
    }
    system("PAUSE");
    return 0;
}
### C++ 中 `std::function` `std::bind` 的用法及区别 #### 定义与基本概念 `std::function` 是一种通用多态函数封装器,可以存储任何可调用对象(如普通函数、lambda 表达式、绑定表达式或其他函数对象)。其灵活性使得它能够作为回调机制的一部分,在事件驱动编程其他场景下非常有用。 ```cpp #include <functional> #include <iostream> void simpleFunction(int a) { std::cout << "Value is: " << a << '\n'; } int main() { // 创建一个 std::function 对象并赋值给简单函数 std::function<void(int)> f = simpleFunction; f(42); } ``` 另一方面,`std::bind` 提供了一种方式来创建新的可调用对象,这些新对象可以通过固定某些参数或将多个可调用实体组合在一起的方式简化现有可调用目标的接口。通过 bind 可以提前设置部分参数,从而减少后续调用时传递相同参数的需求[^1]。 ```cpp #include <functional> #include <iostream> class MyClass { public: void memberFunc(int i, double d) const { std::cout << "Integer value: " << i << ", Double Value:" << d << "\n"; } }; int main(){ using namespace std::placeholders; MyClass obj; // 绑定成员函数到特定实例,并预先设定第一个参数 auto boundMember = std::bind(&MyClass::memberFunc, &obj, _1, 3.14); // 调用已绑定的对象只需要提供剩余未固定的参数即可 boundMember(7); } ``` #### 主要差异点 - **目的不同**: `std::function` 更侧重于作为一个容器去保存各种类型的可调用对象;而 `std::bind` 则专注于调整已有可调用对象的行为模式,比如预设一些输入参数。 - **使用场合的区别**: 当需要定义一个能接受多种不同类型但签名兼容的函数指针的地方时,应该优先考虑使用 `std::function`; 如果想要改变某个具体函数或方法的工作方式,则可以选择 `std::bind`. - **性能考量**: 在大多数情况下,直接使用 lambda 表达式可能比使用 `std::bind` 效率更高,因为后者可能会引入额外的小型分配开销以及间接层。然而对于复杂情况下的参数绑定操作来说,`std::bind` 还是有它的优势所在[^2].
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值