How to make typedef on void function that could be property of any class?
When we do
typedef void FuncCharPtr(char*, int) ;
vector<FuncCharPtr*> FuncVec ;
void Add(FuncCharPtr* f)
{
FuncVec.push_back(f);
}
we do not allow to pass as FuncCharPtr types like
void (someClass::*)开发者_StackOverflowb(char*, int);
void (someOtherClass::*)b(char*, int);
and we want to keep links to functions from both classes in same vector so to be able to call all subscribers at once WITH SOMETHING LIKE
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);
delete[] dataCopy;
}
}
How to solve such problemm?
You can't use a function pointer for this. The class type is a part of the type of a pointer to a member function, so there is no one type that would work.
The best way to accomplish what you want to do is to use the function
class and the bind
function from Boost, C++ TR1, or C++0x.
You can maintain a std::vector<std::function<void(char*, int)> >
and use the bind
function to bind pointers to member functions to the instance of the class on which you want the member function to be called:
struct A { void foo(int) { } };
struct B { void bar(int) { } };
typedef std::function<void(int)> Function;
typedef std::vector<Function> FunctionSequence;
typedef FunctionSequence::iterator FunctionIterator;
FunctionSequence funcs;
A a;
B b;
funcs.push_back(std::bind(&A::foo, &a, std::placeholders::_1));
funcs.push_back(std::bind(&B::bar, &b, std::placeholders::_1));
// this calls a.foo(42) then b.bar(42):
for (FunctionIterator it(funcs.begin()); it != funcs.end(); ++it)
(*it)(42);
精彩评论