我无法使用模板编译此代码

I cannot compile this code using template

本文关键字:编译 代码      更新时间:2023-10-16

我正在尝试编译用c++编写的代码。

我在fifo_list.h

中有这段代码
template <class T>
class FIFO_LIST
{
  public:
  class list_type {
  public:
    T data;
    list_type *next;
    void *operator new(size_t num_bytes)
    {
       block_pool mem_pool;
       void *mem_addr = mem_pool.pool_alloc( num_bytes );
       return mem_addr;
     } // new
   };  // class list_type
   private:
  list_type *list;
  public:
  /** define a handle type to abstract the list_type type */
  typedef list_type *handle
  handle first(void)
  {
    return list;
   } // first
 }

和header queue.h:

#include "fifo_list.h"
template <class T>
class queue : protected FIFO_LIST<queueElem<T> *>
{ 
 public:  
  queueElem<T> *queueStart()
  {
    handle h = first();
    queueElem<T> *elem = get_item( h );
    return elem;
   } 
 }

当我尝试编译时,我有这些错误信息:

include/queue.h: In member function ‘queueElem<T>* queue<T>::queueStart()’:
include/queue.h:100: error: ‘handle’ was not declared in this scope
include/queue.h:100: error: expected ‘;’ before ‘h’
include/queue.h:101: error: ‘h’ was not declared in this scope

我错在哪里?

@Piotr Skotnicki, @Barry我已经这样修改了代码

queueElem<T> *queueStart()
{
  //handle h = first();
  typename FIFO_LIST<queueElem<T> *>::handle h = first();
  queueElem<T> *elem = get_item( h );
  return elem;
 } // queueStart

现在我有这样的错误:

include/queue.h:101: error: there are no arguments to ‘first’ that  depend on a template parameter, so a declaration of ‘first’ must be available

由于某些原因,我找不到一个很好的副本…


handle是与相关的名称。非限定查找不会在基类中找到依赖的名称,因此必须对其进行限定:

typename FIFO_LIST<queueElem<T> *>::handle h = first();
同样,由于first也来自基类,因此需要限定:
typename FIFO_LIST<queueElem<T> *>::handle h = FIFO_LIST<queueElem<T> *>::first();

尽管您可以通过简单地使用this->:

来缩短后一个条件
typename FIFO_LIST<queueElem<T> *>::handle h = this->first();

这是两阶段模板实例化的一个已知问题(这就是我不喜欢它的原因)。

要修复你的代码,使用以下命令:

typename FIFO_LIST<queueElem<T> *>::handle h = this->first();