2012-02-16 53 views
1

我不知道是否需要比下面的代碼更多的信息,但如果需要更多信息,只需說出來,我將發佈剩餘的代碼。當編譯我收到以下錯誤:pthread_create模板函數 - 靜態投射模板類

g++ -c -pipe -O2 -Wall -W -I../../../../QtSDK/Desktop/Qt/4.8.0/gcc/mkspecs/linux-g++ -I. -o main.o main.cpp 
In file included from main.cpp:4: 
TimerManager.h: In function 'void* create_pthread(void*)': 
TimerManager.h:17: error: expected nested-name-specifier before 'TimerManager' 
TimerManager.h:17: error: expected '(' before 'TimerManager' 
TimerManager.h:17: error: expected ';' before 'TimerManager' 
make: *** [main.o] Error 1 

我需要什麼,下面來改變擺脫這些錯誤的?


template<class Object> 
void *create_pthread(void *data) 
{ 
    typename TimerManager<Object> *tm = static_cast<TimerManager<Object> *>(data); 
    return data; 
} 

... 

template<class CallObject> 
class TimerManager { 
    ... 
}; 

... 

template<class CallObject> 
TimerManager<CallObject>::TimerManager() : 
    m_bRunning(false), 
    m_bGo(false), 
    m_lMinSleep(0) 
{ 
    int mutex_creation = pthread_mutex_init(&m_tGoLock, NULL); 
    if(mutex_creation != 0) { 
    throw TimerManager::TimerError(std::string("Failed to create mutex")); 
    } 

    int mutex_cond_creation = pthread_cond_init(&m_tGoLockCondition, NULL); 
    if(mutex_cond_creation != 0) { 
    throw TimerManager::TimerError(std::string("Failed to create condition mutex")); 
    return; 
    } 

    int thread_creation = pthread_create(&m_tTimerThread, NULL, create_pthread<CallObject>, this); 
    if(thread_creation != 0) { 
    throw TimerManager::TimerError(std::string("Failed to create thread")); 
    return; 
    } 
    m_bRunning = true; 
} 
+0

哪一行是第17行(帶有錯誤的那一行?) – templatetypedef 2012-02-16 05:30:27

+0

typename TimerManager * tm = static_cast *>(data); – 2012-02-16 05:32:29

+0

等待 - 在你的'create_pthread'函數之前聲明瞭'TimerManager'嗎? – templatetypedef 2012-02-16 05:33:22

回答

2

我認爲問題是,鑑於訂購你的聲明中,TimerManager類模板尚未聲明你的create_pthread定義之前。因此,編譯器報告錯誤,因爲TimerManager不在範圍內。重新排序函數應該可以解決這個問題。

而且,你不要在該行

typename TimerManager<Object> *tm = static_cast<TimerManager<Object> *>(data); 

typename只需要,如果你正在訪問的TimerManager<Object>內嵌套類型需要一個typename。您應該可以將其刪除而不會出現任何問題。

希望這會有所幫助!