2014-02-07 137 views
3

我试图在模板类中使用嵌套类。请参见下面的代码片段:模板类中嵌套类的问题

template <class T> 
class OutterTemplate { 
public: 
    class InnerBase { 
    protected: 
     const char* name_; 
    public: 
     virtual void print() { 
      cout << name_ << endl; 
     } 

     void setName(const char* n) { 
      name_ = n; 
     } 
    }; 

private: 
    class Inner : public InnerBase { 
     public: 
      virtual void print() { 
       cout << name_; 
       cout << " and "; 
       InnerBase::print(); 
      } 
    }; 
public:  
    static InnerBase* getInner() { 
     return new Inner(); 
    } 
}; 

int main() { 
    auto q = OutterTemplate<int>::getInner(); 
    q->setName("Not working"); 
    q->print(); 
} 

我有错误“错误:‘名_’不是在这个范围内声明”,试图编译这段代码时。我检查“outter”是不是模板类,不存在这样的问题。任何人都可以解释为什么模板类出现此错误,以及如何在模板类内部嵌套类的情况下启用对基类成员的访问?

+1

你需要'this-> name_' – 0x499602D2

+0

@juanchopanza直到尽管我还不确定为什么编译器可以这样做......它必须将“Inner”as和InnerBase定义为相关的类名称...... – IdeaHat

+0

@MadScienceDreams如果您更容易忽略外部类。 InnerBase和Inner都是类模板。 – juanchopanza

回答

1

标准在这一点上很清楚:

14.6.2依赖名称[temp.dep]

3 In the definition of a class or class template, if a base class depends on a template-parameter, the base class scope is not examined during unqualified name lookup either at the point of definition of the class template or member or during an instantiation of the class template or member.

在这里,您OutterTemplate<T>::InnerBase是依赖基类的OutterTemplate<T>::Innercout << name_;涉及不合格的名称查询。这意味着InnerBase将不会被检查。添加this->将补救:

14.6.2.1从属类型[temp.dep.type]

7 If, for a given set of template arguments, a specialization of a template is instantiated that refers to a member of the current instantiation with a qualified-id or class member access expression, the name in the qualified-id or class member access expression is looked up in the template instantiation context.

由于this->是一个类的成员访问表达,这意味着name_将在被查找点OutterTemplate<T>::Inner被实例化,此时name_将在基类中找到。