Search code examples
templatesc++11nested-class

How to declare an object of nested class present in base class


I have a C++ program that I can't compile:

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;
}

when I try to compile it , I get the following error:

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

I am new to concept of templates, and not able to figure out what I'm doing wrong.


Solution

  • Base<T *> is a dependent base-class, so you need to use an explicit scope and a typename keyword:

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