8

If I use a chain of inheritance like 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 variadic template classes I could not 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 fails before any instance of the class is instantiated!

1 Answer 1

8

x is a dependent name in this case, so you must access if as this->x (or bring it into scope by putting a using declaration in your class definition:

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

EDIT

The reason for this is discussed in [temp.res] in the standard. Basically: when the compiler is parsing your template, it sees just x. It has no way of knowing that x depends on the template's parameters (which it does in your case, because it comes from a base class which depends on them). Therefore, the compiler tries to resolve x using what it knows when parsing the template, and fails.

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

The same holds true for using Example<Params...>::x;. That also tells the compiler that x depends on template parameters, and its resolution must be postponed to instanitation.

Sign up to request clarification or add additional context in comments.

1 Comment

Ok, this->x work, but I must say: I don't understand the difference between accessing x and this->x for data members. Can anyone explain why this happens?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.