我想在类模板中使用memcpy。所以我的模板将被限制为任何指向C POD (结构)和char*的链接(当然,结构也可以在其他独立的类中声明)。我希望任何类都能够订阅它的函数(如果它有令人尊敬的输入参数)来强制转换事件。所以我的类现在看起来是这样的:
class IGraphElement{
typedef void FuncCharPtr(char*, int) ;
public:
void Add(FuncCharPtr* f)
{
FuncVec.push_back(f);
}
void CastData(char * data, int length){
for(size_t i = 0 ; i < FuncVec.size(); i++){
char* dataCopy = new char[length];
memcpy(dataCopy, data, length);
FuncVec[i](dataCopy, length);
}
}
private:
vector<FuncCharPtr*> FuncVec ;
};一般来说,我想要的是两件真正的事情(我试着用伪代码解释):
template < typename GraphElementDatataStructurePtrType>
class IGraphElement{
typedef void FuncCharPtr(GraphElementDatataStructurePtrType, int) ; // here I want FuncCharPtr to be of type (AnyClassThatWantsToConnectToThisGraphElement::*)(GraphElementDatataStructurePtrType, int)
public:
void Add(FuncCharPtr* f)
{
FuncVec.push_back(f);
}
void CastData(GraphElementDatataStructurePtrType data, int length){
for(size_t i = 0 ; i < FuncVec.size(); i++){
GraphElementDatataStructurePtrType dataCopy = new GraphElementDatataStructurePtrType[length];
memcpy(dataCopy, data, length);
FuncVec[i](dataCopy, length);
}
}
private:
vector<FuncCharPtr*> FuncVec ;
};我想要的东西是如何实现的,以及如何在我的类中实现它?(对不起-我是c++ nube=()
发布于 2011-01-30 18:48:06
boost::signals库已经解决了您的问题。
如果您对内部工作原理感兴趣,可以尝试使用boost::function和boost::bind库实现类似的功能。
您可以研究Modern C++ Design以了解函数器模板的内部工作原理的详细信息,或者只需google&询问此论坛即可。
下面是一个使用boost的sketch解决方案代码:
void DataCastHelper (boost::funtion funcCharPtr, char * data, int length) {
char* dataCopy = new char[length];
memcpy(dataCopy, data, length);
funcCharPtr(dataCopy, length);
}
class IGraphElement {
public:
void Add (FuncCharPt* f) {
funcVec.connect(boost::bind(&DataCastHelper, f, _1, _2));
}
void CastData(char * data, int length){
funcVec(data. length);
}
private:
boost::signal<FuncCharPtr> funcVec;
}传递给IGraphElement::Add方法的FuncCharPt* f参数是将与DataCastHelper堆叠在一起,以便为您复制数据。信号处理函数器的迭代和调用,并将参数传递给函数器。
问候
https://stackoverflow.com/questions/4841792
复制相似问题