为什么我不能使用模板类的父类变量?

Gim*_*Eom 6 c++ inheritance templates

template <typename T>
class A
{
    public:
    int a;
}
Run Code Online (Sandbox Code Playgroud)

BH

template <typename T>
class B : public A<T>
{
   public:
   int f();
}

template <typename T>
int B<T>::f()
{
    int t;
    t = this->a; //Okay
    t = a //Error
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

为什么我不使用时会发生错误this->

我可以省略this->使用某种方法吗?

(我修正了一些错误)

Seb*_*ach 12

模板实例化有两个阶段("两阶段名称查找").

在第一阶段,解析所有非依赖名称(查找).在第二阶段,依赖名称被解析.

从属名称是依赖于模板参数的名称,例如:

template <typename T>
void foo() {
    x = 0;    // <- Non-dependent, nothing in that refers to "T".
              //    Thus looked up in phase 1, therefore, an 'x' must be
              //    visible.

    T::x = 0; // <- Dependent, because it depends on "T".
              //    Looked up in phase 2, which is when it must be visible.
}
Run Code Online (Sandbox Code Playgroud)

现在,你写道:

t = this->a; //Okay
t = a //Error
Run Code Online (Sandbox Code Playgroud)

这正是我所描述的.在好的术语中,t在第2阶段查找,因为this取决于模板参数.

在阶段1中查找错误的术语,因为该名称中的任何内容都不依赖于模板参数.但是在阶段1中,没有a可见,因为编译器无法在阶段1中内省基类模板,因为模板可以是专用的,并且在实例化时,可以远离主模板声明,另一个没有的专门化a,可能是可见的.

例:

    template <typename T>
    struct Base {
    };


    template <typename T>
    struct Derived : Base<T> {
        void foo() {
            this->a = 0; // As is valid. `this->a` is looked up in phase 2.
        }
    };


    template <> struct Base<int> {
        int a;            
    };


    int main () 
    {
            // The following declarations trigger phase 2 lookup.

            Derived<int>   di;  // valid, because a later specialized
                                // Base<int> is used and all symbols
                                // are resolved.

            Derived<float> df;  // not valid
    }
Run Code Online (Sandbox Code Playgroud)

顺便说一下,我曾经写过这个 - >不仅仅是我的低频博客中的风格问题.