2012-02-16 71 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。您应该可以将其删除而不会出现任何问题。

希望这会有所帮助!