pthread_create模板函数 - 静态转换模板类

时间:2012-02-16 05:26:00

标签: c++ templates casting callback pthreads

我不知道是否需要比下面的代码更多的信息,但如果需要更多信息,只需这样说,我将发布剩余的代码。编译时我收到以下错误:

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

1 个答案:

答案 0 :(得分:2)

我认为问题是,鉴于您对声明的排序,TimerManager类模板在您定义create_pthread之前尚未声明。因此,编译器报告错误,因为TimerManager不在范围内。重新排序功能应该解决这个问题。

此外,行

中不需要typename
typename TimerManager<Object> *tm = static_cast<TimerManager<Object> *>(data);
只有在typename内访问嵌套类型时才需要

TimerManager<Object>。你应该可以毫无问题地删除它。

希望这有帮助!