2011-01-30 26 views
1

當我們做如何使void屬性可以是任何類的void函數?

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

我們不允許通過爲FuncCharPtr類型,如

void (someClass::*)b(char*, int); 
void (someOtherClass::*)b(char*, int); 

,我們要保持鏈接在同一載體中這兩類功能,所以能夠將所有來電訂戶立刻與像有點像

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; 
    } 
} 

如何解決這樣problemm?

回答

6

您不能爲此使用函數指針。類的類型是指向成員函數的指針類型的一部分,因此沒有可用的類型。

完成你想要做的最好的方法是使用來自Boost,C++ TR1或C++ 0x的the function classthe bind function

可以保持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); 
+0

你能提供任何鏈接或代碼示例如何實現std :: vector >解決方案?這將是真正的爐火! – Rella 2011-01-30 21:21:15

相關問題