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

标签 c++ templates inheritance

啊啊

template <typename T>
class A
{
    public:
    int a;
}

b.h

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;
}

为什么不使用this->会出错?

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

(我修正了一些错误)

最佳答案

模板实例化有两个阶段(“两阶段名称查找”)。

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

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

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.
}

现在,你写:

t = this->a; //Okay
t = a //Error

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

在第 1 阶段查找错误的术语,因为该名称中的任何内容都不依赖于模板参数。 但是在阶段 1 中,没有 a 是可见的,因为编译器无法内省(introspection)基类模板 在第 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
    }

顺便说一句,我曾经写过 this-> is not only a matter of style 在我的频率非常低的博客中。

关于c++ - 为什么我不能使用作为模板类的父类的变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10171242/

相关文章:

c++ - 类 union 类和变体成员

c++ - 我似乎无法修复的意外错误

PHP:如何从父类调用子类的函数

c++ - 模板模板 C++ 函数

C++ 重载运算符,解引用引用

c++ - 派生类对象是否包含基类的私有(private)成员?它在内存中是什么样子的?

c++ - 在32位数字中查找第一个(最低)置位位置

c++ - 在排序模板函数中确定 2 个数组差异组件

c++ - Swift 中的神经网络

c++ - 是作者炫耀还是真实的做法