Template class with nested classes

1 #include <iostream>
2 using namespace std;
3 template<typename T>
4 class Top {
5 public:
6     class Sub {
7         protected:
8             T age;
9     };
10     class Derived : public Sub {
11         public:
12             void printAge() {
13                 cout << age << endl;
14             }
15     };  
16 };
17 int main()
18 {
19     return 0;
20 }

when I follow the codes, I get the following errors:

test.cpp: In member function ‘void Top<T>::Derived::printAge()’:
test.cpp:13:25: error: ‘age’ was not declared in this scope
             cout << age << endl;

But if this is not a template, everything will be fine. I am glad to receive your answers.

+4
source share
3 answers

Age in Derived is the name inside the template. There are two types of names defined by the standard:

  • Dependent: names depending on template parameters, but arent declared in the template.
  • Independent: names that are independent of the template parameters, plus the name of the template itself and the names declared in it.

cout << age << endl - , . , , Top:: sub / . , . , .

- > Top:: , . , .

+1
class Top<T>::Derived : public Top<T>::Sub

- Derived. , Sub T. , template, (Sub::age), (this->age).

, , T, , . ( , ).

, , this->age .

0

age , . , . () ( ), memeber ( "" ) . , , memeber .

- memeber this, .

0

All Articles