近期在项目开发过程中,很苦恼设置回调函数时,需要写个全局静态函数转换一下的实现方式,了解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;
}