如何在void函数上创建typedef,它可以是任何类的属性?

Rel*_*lla 1 c++ oop typedef vector visual-studio

当我们这样做

typedef void FuncCharPtr(char*, int) ;
vector<FuncCharPtr*> FuncVec ;
void Add(FuncCharPtr* f)
{
    FuncVec.push_back(f);
}
Run Code Online (Sandbox Code Playgroud)

我们不允许以FuncCharPtr类型传递

 void (someClass::*)b(char*, int);
 void (someOtherClass::*)b(char*, int);
Run Code Online (Sandbox Code Playgroud)

并且我们希望保持链接到同一向量中的两个类的函数,以便能够一次性调用所有订阅者与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;
    }
}
Run Code Online (Sandbox Code Playgroud)

如何解决这样的问题?

Jam*_*lis 6

您不能使用函数指针.类类型是指向成员函数的指针类型的一部分,因此没有一种类型可以工作.

完成你想做的事,最好的办法就是使用function,并bind功能与Boost,C++ TR1,或C++ 0x中.

您可以维护std::vector<std::function<void(char*, int)> >并使用该bind函数将指向成员函数的指针绑定到要在其上调用成员函数的类的实例:

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);
Run Code Online (Sandbox Code Playgroud)