c++.指向模板函数的函数指针产生未解析的重载函数类型错误

c++. function pointer to template function produces unresolved overloaded function type error

本文关键字:函数 错误 类型 重载 指针 c++      更新时间:2023-10-16

我需要让一个类方法将一个模板函数作为指向函数参数的指针,然后调用它。

但我遇到了

ThreadPool.hh:55:2: error: no matching function for call to ‘ThreadPoolElem<int>::start(<unresolved overloaded function type>, ThreadPoolElem<int>*)’

我的代码示例和解释如下:

我有一个主模块ThreadPool,它有一个ThreadPoolElem向量。正如您可能已经猜到的那样,ThreadPoolElem是Threads的封装,ThreadPool扮演线程池管理器的角色。我需要从ThreadPool迭代threadPoolElem向量。对于向量中的每个元素,我需要调用其"start"成员函数,该函数包含2个自变量(第一个自变量是指向函数的指针)。在ThreadPoolElem类的"start"成员函数中,它使用第一个参数作为第三个pthread_create c库函数的回调。

我的线程池文件是这样的:

template <typename T>
class ThreadPool
{
 Mutex _mutex;
 CondVar _condVar;
 SafeQueue<T> _tasks;
 std::vector<ThreadPoolElem<T> > _threadVector;
 /* .... */
   void run(void)
 {
 for (typename std::vector<ThreadPoolElem<T> >::iterator it =    this>_threadVector.begin();
     it != this->_threadVector.end();
     ++it)
  {
    it->start(run_tramp, &(*it));
  }
 }

我的ThreadPoolElem文件如下:

template <typename T>
 class ThreadPoolElem : public ThreadT<T>
 {
 SafeQueue<T> *_tasks;
 CondVar *_condVar;
 Mutex *_mutex;
 public:
 ThreadPoolElem(void) {}
  void init(SafeQueue<T> *queue, CondVar *condVar, Mutex *mutex){
  this->_mutex = mutex;
  this->_condVar = condVar;
  this->_tasks = queue;
   }
  void run(void){
  while (true)
   {
    this->_mutex.lock();
    if (this->_tasks.empty())
      {
        this->_condVar->wait();
        this->_mutex->unlock();
      }
    else
      {
        int value;
        this->_tasks->tryPop(&value);
        std::cout << "consuming value" << std::endl;
        if (!this->_tasks->empty())
          {
            this->_mutex->unlock();
            this->_condVar->signal();
          }
        else
          this->_mutex->unlock();
      }
      }
    }
   };

这是一个类似c的函数(蹦床函数),我需要将其作为函数参数的ptr

  template <typename T>
  void    *run_tramp(void *data)
  {
   reinterpret_cast<ThreadPoolElem<T> *>(data)->run();
   return NULL;
  }

最终的相关文件是:

template <typename T>
class ThreadT
{
 public:
 typedef enum
 {
  NOT_YET_STARTED,
  RUNNING,
  DEAD,
  }thread_status;
  private:
  thread_status status_;
   pthread_t     thread_;
  public:
/* .... */
   void start(void *(*ptr)(void *), void* data){
  this->status_ = RUNNING;
   if (pthread_create(&this->thread_, NULL, ptr, data) != 0)
   throw (SystemError("pthread_create"));
   }
    /* ...... */
};

当您将指向'rampoline函数'的指针传递给ThreadT<T>::start()方法时,您没有使用模板化函数实例化,您需要指定它应该为哪个T实例化:

it->start(run_tramp<T>, &(*it));
                // ^^^