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

时间:2015-10-21 17:20:41

标签: c++ templates inheritance

我正在尝试编译用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

 }

和此标题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

2 个答案:

答案 0 :(得分:2)

出于某种原因,我找不到这个好的副本......

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();

答案 1 :(得分:1)

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

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

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