std::bind绑定类成员函数的示例

近期在项目开发过程中,很苦恼设置回调函数时,需要写个全局静态函数转换一下的实现方式,了解C++新特性里面的std::bind之后,感觉使用起来非常简单方便,于是写了个测试用例(代码中利用普通类和单例类进行了测试)做了个测试,效果比较好。

#include <iostream>
#include <functional>

class General
{
public:
	General() {}

	~General() {}

	void func(void* pVal)
	{
		int* pIntVal = static_cast<int*>(pVal);
		std::cout << "General::func, " << *pIntVal << std::endl;
	}
};

class Single
{
public:
	static Single* instance()
	{
		static Single obj;
		return &obj;
	}

	void func(void* pVal)
	{
		int* pIntVal = static_cast<int*>(pVal);
		std::cout << "Single::func, " << *pIntVal << std::endl;
	}

private:
	Single() {}
	~Single() {}
};

class TestInfo
{
public:
	TestInfo() { m_func = nullptr; }
	~TestInfo() {}

	void test(int *pVal)
	{
		if (m_func)
		{
			m_func(pVal);
		}
	}

	std::function<void(void*)> m_func;
};


void stdBindTest()
{
	General gen;
	TestInfo test1;
	//test1.m_func = std::bind(&General::func, &gen, nullptr); // 可以写死,但是不建议这么使用
	test1.m_func = std::bind(&General::func, &gen, std::placeholders::_1); // 占位符,便于后续传参数
	int* pVal1 = new int(123);
	test1.test(pVal1);
	delete pVal1;

	TestInfo test2;
	//test2.m_func = std::bind(&Single::func, Single::instance(), nullptr); // 可以写死,但是不建议这么使用
	test2.m_func = std::bind(&Single::func, Single::instance(), std::placeholders::_1); // 占位符,便于后续传参数
	int* pVal2 = new int(345);
	test2.test(pVal2);
	delete pVal2;

	return;
}

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值