2013-03-05 61 views
1

我正在進行優化項目,並決定嘗試線程以提高代碼的速度。代碼的格式是:boost線程錯誤<未解析的重載函數類型>

Main.cpp的:

int main(int argc, char **argv) { 
    B *b = new B(argv[1]); 
    b->foo(); 
    delete b; 
    return EXIT_SUCCESS; 
} 

B.cpp:

#include B.hpp 

B::B(const char *filename) { .... } 

B::task1(){ /*nop*/ } 

void B::foo() const { 
    boost::thread td(task1); 
    td.join(); 
} 

B.hpp:

#include <boost/thread.hpp> 

class B{ 
    public: 
    void task1(); 
    void foo(); 
} 
然而

,當我嘗試編譯此代碼,我在boost::thread td(task1)得到一個錯誤,說:

error: no matching function for call to 'boost::thread::thread(<unresolved overloaded function type>)'

不完全確定問題出在哪裏,我嘗試過黑客攻擊沒有成功。任何幫助表示讚賞!

編輯:新的錯誤

B.o: In function 'B::b() const': 
B.cpp:(.text+0x7eb): undefined reference to 'vtable for boost::detail::thread_data_base' 
B.cpp:(.text+0x998): undefined reference to 'boost::thread::start_thread()' 
B.cpp:(.text+0x9a2): undefined reference to 'boost::thread::join()' 
B.cpp:(.text+0xa0b): undefined reference to 'boost::thread::~thread()' 
B.cpp:(.text+0xb32): undefined reference to 'boost::thread::~thread()' 
B.o: In function 'boost::detail::thread_data<boost::_bi::bind_t<void, boost::_mfi::cmf0<void, B>, boost::_bi::list1<boost::_bi::value<B const*> > > >::~thread_data()': 
B.cpp:(.text._ZN5boost6detail11thread_dataINS_3_bi6bind_tIvNS_4_mfi4cmf0Iv4BEENS2_5list1INS2_5valueIPKS6_EEEEEEED2Ev[_ZN5boost6detail11thread_dataINS_3_bi6bind_tIvNS_4_mfi4cmf0Iv4BEENS2_5list1INS2_5valueIPKS6_EEEEEEED5Ev]+0x8): undefined reference to 'boost::detail::thread_data_base::~thread_data_base()' 

回答

3

B::task()是一個構件的功能,所以它需要B*類型的隱式第一個參數。所以你需要傳遞一個實例給它,以便在boost::thread中使用它。

void B::foo() const { 
    boost::thread td(&B::task1, this); // this is a const B*: requires task1() to be const. 
    td.join(); 
} 

但由於B::foo()const方法,你將不得不作出一個B::task1()方法const太:

class B { 
    void task1() const: 
} 
+0

在簡化我的代碼,我可能已經可能過於簡單 - 我的'B'類有一個需要在'task1()'中使用的成員變量。創建一個新的B並綁定它會阻止我使用對象變量,不是嗎? – ElFik 2013-03-05 20:37:51

+0

@ElFik該示例僅用於說明。你可以傳遞'this'而不是'&b'。 '這是''B *'。 – juanchopanza 2013-03-05 20:39:20

+0

@ElFik我改變了這個例子,從'B'的一個方法中開始線程。 – juanchopanza 2013-03-05 20:45:01

相關問題