Recursive inheritance with variable patterns and inherited parameters

If I use the inheritance chain, as in the following example, I could use vars from the deepest base without any problems:

class A { public: int x; }; class B : public A { }; class C: public B { public: void Do() { cout << x << endl; } }; 

If I do the same with recursive variational template classes, I would not be able to access my vars. Any idea how to access the vars and why I could not see my vars?

  template <class ...Parms> class Example; template <class Head, class ...Parms> class Example<Head, Parms...>: public Example<Parms...> { }; template <> class Example<> { public: int x; }; template <class ...Parms> class Last: public Example<Parms...> { void Do() { cout << x << endl; } }; 

Compile the crash before any class instance is instantiated!

+6
source share
1 answer

x is a dependent name in this case, so you should access it as this->x (or enter it in scope by placing a declaration of use in the class definition:

 using Example<Params...>::x; 

EDIT

The reason for this is discussed in [temp.res] in the standard. Basically: when the compiler parses your template, it only sees x . He does not know that x depends on the template parameters (what does it do in your case, because it comes from the base class, which depends on them). Therefore, the compiler tries to resolve x using what it knows when parsing the template, and fails.

The notation this->x means that x refers to a member of the class; since the base class of your particular class depends on the template parameters, the compiler knows that when parsing the template it cannot resolve x and will postpone the resolution until the template is instantiated. At that time, template arguments were known.

The same is true for using Example<Params...>::x; . It also tells the compiler that x depends on the template parameters, and its resolution should be delayed until instanitation.

+6
source

All Articles