如何声明基类中存在的嵌套类的对象

时间:2015-04-27 12:16:02

标签: templates c++11 nested-class

我有一个无法编译的C ++程序:

template <class T>
class Base
{
  protected:
   class BaseNode
    {
          public:
             int i;
 };
 protected:
    typedef void (*functionPointer)(const T &t, void *data);
    virtual void apply( const functionPointer fn,  void *data) const;
};

template <class T>
class Derived : public Base<T *>
{
  public:
    typedef void (*functionPointer)(const T *t, void *data);
    virtual void apply( const functionPointer fn,  void *data) const;
};

template <class T> void Derived<T>::apply(  const functionPointer fn,
                                                 void           *data) const
{
   BaseNode *node ;
}
int main()
{
 Derived<int > b;
}

当我尝试编译它时,我收到以下错误:

pankajk[]> g++ sample2.cpp
sample2.cpp: In member function 'virtual void Derived<T>::apply(void (*)(const T*, void*), void*) const':
sample2.cpp:26: error: 'BaseNode' was not declared in this scope
sample2.cpp:26: error: 'node' was not declared in this scope

我是模板概念的新手,无法弄清楚我做错了什么。

1 个答案:

答案 0 :(得分:2)

Base<T *>是依赖基类,因此您需要使用显式范围和typename关键字:

template <class T> void Derived<T>::apply(const functionPointer fn,
                                                 void           *data) const
{
    typename Base<T *>::BaseNode* node;
//  ~~~~~~~^ ~~~~~~~~^          
}