2011-11-22 66 views
1

我正在嘗試使用boost :: bind傳遞函數指針。將綁定回調函數指針作爲參數

void 
Class::ThreadFunction(Type(*callbackFunc)(message_type::ptr&)) 
{ 
} 

boost::shared_ptr<boost::thread> 
Class::Init(Type(*callbackFunc)(message_type::ptr&)) 
{ 
    return boost::shared_ptr<boost::thread> (
     new boost::thread(boost::bind(&Class::ThreadFunction, callbackFunc)) 
     ); 
} 

我收到以下錯誤:

1>C:\dev\sapphire\boost_1_46_1\boost/bind/mem_fn.hpp(362) : warning C4180: qualifier applied to function type has no meaning; ignored 
1>C:\dev\sapphire\boost_1_46_1\boost/bind/mem_fn.hpp(333) : error C2296: '->*' : illegal, left operand has type 'Type (__cdecl **)(message_type::ptr &)' 

不過,我能換到下面,它工作正常:

void 
ThreadFunction(Type(*callbackFunc)(message_type::ptr&)) 
{ 
} 

boost::shared_ptr<boost::thread> 
Class::Init(Type(*callbackFunc)(message_type::ptr&)) 
{ 
    return boost::shared_ptr<boost::thread> (
     new boost::thread(boost::bind(&ThreadFunction, callbackFunc)) 
     ); 
} 

爲什麼我得到,如果我這些錯誤在Class類中聲明該方法?

回答

3

當你綁定一個非靜態成員函數時,你需要提供this將被使用的指針。如果您不想使用與特定實例Class相關的函數,則應該使函數靜態。

struct Class { 
    void foo(int) { } 
    static void bar(int) { } 
}; 

std::bind(&Class::foo, 5); // Illegal, what instance of Class is foo being called 
          // on? 

Class myClass; 
std::bind(&Class::foo, &myClass, 5); // Legal, foo is being called on myClass. 

std::bind(&Class::bar, 5); // Legal, bar is static, so no this pointer is needed. 
+1

+1,我忘記提及使用成員函數的替代方案。 – Anthony

2

因爲您還需要綁定Class的實例。閱讀Boost documentation

認爲你需要這樣的:

boost::thread(boost::bind(
    &Class::ThreadFunction, &someClassInstance, _1), 
    callbackFunc); 

注:上面的代碼片斷是從我的頭頂。我認爲這是正確的。

+0

足夠接近,但佔位符位於未命名的名稱空間中。 –

+0

@dauphic,謝謝。 – Anthony

相關問題