Home > Blockchain >  Why are unqualified names from nondependent base classes favored over template parameters
Why are unqualified names from nondependent base classes favored over template parameters

Time:04-06

The C standard says that unqualified names from nondependent base classes are preferred over template parameters. What is the reasoning behind this?

The following snippet is from C Templates:

#include <iostream>

template <typename X>
class Base {
    public:
        int basefield;
        using T = int;
};

class D1 : public Base<Base<void>> {
    public:
        void f() { basefield = 3; // works as normal 
        }
};

template <typename T>
class D2 : public Base<double> {
    public:
        void f() { basefield = 7; }
        T strange;  // what type am I ???
};

int main() {
    D2<std::string> d;
    d.strange = 100;
}

CodePudding user response:

Unqualified lookup is approximately equivalent to trying a qualified lookup in each containing scope and keeping the first hit. Since D2<…>::T can find Base<double>::T, it is the lookup in the class’s scope that succeeds; that lookup naturally precedes that for the template parameters that are introduced lexically outside the class.

CodePudding user response:

// what type am I ???

When an unqualified name is looked up in the templated derivation(like D2), the nondependent bases are considered before the list of template parameters.

In your case, this means that, the member strange of the class template D2 always has the type T corresponding to Base<double>::T (which is nothing but, int).

You can confirm this by changing d.strange = 100; to:

d.strange = "100"; //this will give error saying: invalid conversion from ‘const char*’ to ‘Base::T’ {aka ‘int’}

The above statement produces the error saying:

invalid conversion from ‘const char*’ to ‘Base::T’ {aka ‘int’} which confirms that strange has type int.


What is the reasoning behind this?

One reason for why the standard says so might be because as the lookup starts for a name, it goes upwards(in the up direction) from where the name was encountered. Now, while searching for the name in the upward direction, the non-dependent Base is encountered first and so the name is resolved belonging to the non-dependent Base(obviously the Base must have a member which is named the same that is being looked up). On the other hand in case of a dependent Base, the template parameter must first be known in order for the dependent Base to be known. This is my current reasoning of why the standard says so.

Please correct me in the comment if/when i am wrong and i will remove this part of the answer.

  • Related