为什么我不能使用父类的变量作为模板类? [英] Why can't I use variable of parent class that is template class?

查看:218
本文介绍了为什么我不能使用父类的变量作为模板类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

a.h

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

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

为什么当我不使用 this->

我可以使用一些方法省略 this-> 方法?

Can I omit this-> with using some method?

(我修正了一些错误)

推荐答案

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

There are two phases in template instantiation ("Two Phase Name Lookup").

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

In the first phase, all non-dependent names are resolved (looked up). In the second phase, dependent names are resolved.

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

A dependent name is a name that does not depend on a template parameter, e.g.:

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

这正是我所描述的。在好的期限中,在阶段2,
中查找 t ,因为这个取决于模板参数。

This is exactly what I described. In the okay term, t is looked up in phase 2, because this depends on a template parameter.

在阶段1中查找错误的术语,因为该名称中没有任何内容取决于模板参数。
但是在阶段1中,没有 a 可见,因为编译器不能在阶段1中忽略基类模板
,因为模板可以是专门的,实例化点
可以远离主模板声明,另一个没有 a 的专用化
可能是可见的。

The errorful term is looked up in phase 1, because nothing in that name depends on a template parameter. But in phase 1, no a is visible, because the compiler cannot introspect base class templates in phase 1, because templates can be specialized and at the point of instantiation, which can be remote from the primary template declaration, another specialization that has no a, might be visible.

示例:

    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
    }

Btw,我曾经写过 this->不仅仅是风格的问题, / a>

Btw, I have once written this-> is not only a matter of style in my very low frequency blog.

这篇关于为什么我不能使用父类的变量作为模板类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆