来自基本模板类的指针在派生模板类中看不到

时间:2015-06-21 13:16:34

标签: c++ templates inheritance

我有模板类List:

template<class T>
class List{
    protected:
    element<T>* head;
//...
};

我有从List继承的模板类Set:

template<class T>
class Set: public List<T>{
    public:
    void insert(const T& t){
        if(!has(t))
            pushFront(t);
    }
    bool has(const T& t){
        bool is=false;
        element<T>* tmp=head;
        while(tmp && !is){
            if(Comparator::compare(t, tmp->key))
                is=true;
            tmp=tmp->next;
        }
        return is;
    }
};

我的问题是,当我想在没有任何其他内容的情况下使用行element<T>* tmp=head;时,我会收到错误'head' was not declared in this scope,但是当我在此行前面添加List<T>::时{{1}一切正常。为什么我得到这个错误,当head受到保护并且我使用公共继承?

1 个答案:

答案 0 :(得分:0)

这是因为分配了&#34; element<T>* tmp&#34;不要去掉T参数, 所以,tmp被称为非独立名称。另一方面,List依赖于 模板参数T so List称为从属名称。

问题:查找时,编译器不会查找依赖的基类(如List) 非独立名称(如头部)。

解决方案:

  1. 将通话从头部更改为此 - > head。由于这总是隐含地依赖于模板, this-&gt; head是依赖的,因此查询被推迟到模板实际被实例化为止, 此时考虑所有基类。
  2. 将来电从tmp = head更改为element<T>::head。这是您目前的解决方案,但请注意...... 如果head是一个虚函数,这可能不会给你你想要的东西,因为它会禁止虚拟 派遣机制。
相关问题