经常我们做业务共用代码 HPP 时, 希望CPPx1包含的时候有自己的实现函数, CPPx2是另外一个.
那么怎么在HPP动态调用不同的实现呢? 一下是做了个例子. 其实还可以使用 模板类检测类内是否有某个函数或者成员变量. https://blog.csdn.net/sinat_18811413/article/details/104606673
点击(此处)折叠或打开
- #include <thread>
- #include <functional>
- #include <iostream>
- #include <ostream>
- #include <unistd.h>
- using namespace std;
- /*
- g++ cpp_func_ptr.cpp -lpthread
- */
- class CTest;
- typedef void (CTest::*CUST_CB)();
- class CTest
- {
- public:
- std::thread m_thread ;
- CTest()
- {
- //cb = &CTest::custom_cb;
- m_thread = std::thread(std::bind(&CTest::execute, this));
- }
- void custom_cb()
- {
- cout << "callback OK" << endl;
- }
- void regist_cb(CUST_CB pfunc_cb)
- {
- cb = pfunc_cb;
- }
- void execute(void)
- {
- while (1) {
- if (cb) {
- (this->*cb)();
- }
- sleep(1);
- }
- }
-
- CUST_CB cb{nullptr};
- };
- int main()
- {
- CTest test;
- test.regist_cb(&CTest::custom_cb);
- test.execute();
- }