Access protected member of a class in a derived class

后端 未结 2 1144
我在风中等你
我在风中等你 2020-12-11 03:36

i have an old codebase here, where they used protected member variables. Whether or not this is a good idea can be discussed. However, the code must have compiled fine with

2条回答
  •  有刺的猬
    2020-12-11 04:08

    The expression x used in the derived class is, by the rules in the standard, not dependent on any template parameter of the derived class. Because of this, lookup happens in the context of the template definition and not at the point of use/instantiation. Even though the template base class of the template appears to be visible, because it is a template class the particular instantiation that might be used might involve specialized templates so the base class template definition cannot be used for name lookup.

    By changing the expression to this->x you are making it a dependent expression (this in a class template always depends on the template parameters). This means that lookup will occur in the instantiation context at which point the base class is fully known and its members are visible.

提交回复
热议问题