简体   繁体   中英

Using and re-defining typedef from base class

Is it legal for a name to refer to a base class member in one part of class definition and to a derived class member in another? This code demonstrates it:

struct Base
{
  typedef int T;
};


struct Derived : Base
{
  T m1; //type int
  typedef T *T;
  T m2; //type int*
};

I haven't been able to find a ruling against this in the standard. Is the code legal?

Luckily in this case it doesn't matter whether it's legal or not (I believe that it's well-formed because typedefs are allowed to shadow) because you can make a tiny refactor change and the code become completely obvious:

struct Derived : Base
{
  typedef Base::T BaseT;
  typedef BaseT* T;

  BaseT m1; //type int
  T m2; //type int*
};

I believe it's legal ( typedef are certainly processed in the order they appear), but it will be TERRIBLY confusing for anyone trying to read the code in the future.

It would make much more sense to rename the secondary type:

 typedef T *Tptr; 
 Tptr m2;

Yes, it is legal. I will make no comment on whether or not it's advisable.

First, you need to be able to redeclare a different entity with the same name in the derived class; this is allowed by 3.3.10/1 (with my emphasis):

A name can be hidden by an explicit declaration of that same name in a nested declarative region or derived class .

Then you need T to refer to Base::T in the declaration of the Derived::T ; ie Derived::T must not be in scope at that point. The scope is defined by 3.3.3/1:

Its potential scope begins at its point of declaration and ends at the end of its block.

and the point of declaration is defined by 3.3.2/1:

The point of declaration for a name is immediately after its complete declarator

meaning that, before and during the declarator, Derived::T is not in scope and so T refers to Base::T .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM