#include "stdafx.h"
#include <vector>
#include<string>
#include<sstream>
#include<iostream>
#include<iomanip>
#include<string>
#include<stack>
#include<map>
#include<iostream>
#include<algorithm>
#include <thread>
#include<windows.h>
#include"tchar.h"
#include <stdio.h>
#include <string.h>
#include <set>
#include <thread>
using namespace std;
template <class T, class M>
class ShmReceiver {
public:
explicit ShmReceiver(std::string topidName, uint32_t blockNum, void(*fp)(M));
explicit ShmReceiver(std::string topidName, uint32_t blockNum, void (T::*fp)(M), T* obj);
~ShmReceiver();
void ShmReadTreadFunc();
void HandleMessage();
private:
std::thread receiverThread_;
uint32_t blockNum_;
std::string topidName_;
uint32_t dataSize_;
std::function<void(M)> callback;
};
template<class T, class M>
void ShmReceiver<T, M>::HandleMessage()
{
std::cout << "线程运行" << std::endl;
std::string data = "111";
callback(data);
}
template<class T, class M>
void ShmReceiver<T, M>::ShmReadTreadFunc()
{
receiverThread_ = std::thread(&ShmReceiver::HandleMessage, this);
receiverThread_.detach();
}
template<class T, class M>
ShmReceiver<T, M>::ShmReceiver(std::string topidName, uint32_t blockNum, void(*fp)(M))
{
topidName_ = topidName;
dataSize_ = sizeof(M);
blockNum_ = blockNum;
callback = fp;
}
template <class T, class M>
ShmReceiver<T, M>::ShmReceiver(std::string topidName, uint32_t blockNum, void (T::*fp)(M), T* obj)
{
topidName_ = topidName;
dataSize_ = sizeof(M);
blockNum_ = blockNum;
callback = bind(fp, obj, std::placeholders::_1);
}
template<class T, class M>
ShmReceiver<T, M>::~ShmReceiver()
{
}
class UserHandle
{
public:
UserHandle() {};
~UserHandle() {};
void printScreen(std::string data) {
std::cout << "hello world: " <<data<< std::endl;
}
};
void printS(std::string darar)
{
std::cout << "hello world: " << darar << std::endl;
}
int main()
{
std::string topicName = "test";
uint32_t blockNum = 10;
UserHandle *users = new UserHandle();
//ShmReceiver<UserHandle, std::string> *readPtr = new ShmReceiver<UserHandle, std::string>(topicName, blockNum, printS);
//readPtr->ShmReadTreadFunc();
ShmReceiver<UserHandle, std::string> *readPtr2 = new ShmReceiver<UserHandle, std::string>(topicName, blockNum, &UserHandle::printScreen, users);
readPtr2->ShmReadTreadFunc();
system("pause");
}
上图图展示了两类回调函数的框架。