Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why are methods and attributes of base template classes not immediately available? [duplicate]

Tags:

c++

templates

Why is it that the C++ standard specify that unqualified names in a template are non-dependent?

e.g.

template<typename T>
class Base
{
public:
    T x;
};

template<typename T>
class C : public Base<T>
{
public:
    bool m() { return x == 0; } // Error: undeclared identifier 'x'
};

Quoting from the accepted answer to an SO question about how to overcome the restriction:

The standard specifies that unqualified names in a template are non-dependent and must be looked up when the template is defined. The definition of a dependent base class is unknown at that time (specializations of the base class template may exist) so unqualified names are unable to be resolved.

However, the quoted and other answers do not specify why this is what the standard specifies. What is the rationale for this restriction?

like image 447
Danra Avatar asked Nov 16 '25 12:11

Danra


1 Answers

This isn't quite what the standard actually says. What it actually says is that dependent base classes are not examined during unqualified name lookup. An unqualified name can of course be dependent given the correct context - that's how ADL in templates works: given a template type parameter T, the foo in foo(T()) is a dependent name.

In any event, the reason it can't do this kind of lookup is straightforward: at template definition time, you have no idea what the dependent base class is going to look like, thanks to specializations that may come in later, so you can't do any meaningful lookup. Every misspelled identifier in a template with a dependent base class can't be diagnosed until when it is instantiated, if ever. And since every unqualified identifier might have been from a dependent base class, you'll need some way to answer "is this a type?" and "is this a template?", since the answers to those questions affect parsing. That means something like the dreaded typename and template keywords, but in far more places.

like image 138
T.C. Avatar answered Nov 19 '25 02:11

T.C.