本文介绍了为什么派生模板类不能访问基本模板类的标识符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请考虑:

template <typename T>
class Base
{
    public:
        static const bool ZEROFILL = true;
        static const bool NO_ZEROFILL = false;
}

template <typename T>
class Derived : public Base<T>
{
    public:
        Derived( bool initZero = NO_ZEROFILL );    // NO_ZEROFILL is not visible
        ~Derived();
}



我不能用GCC g ++ 3.4.4(cygwin)编译。

I am not able compile this with GCC g++ 3.4.4 (cygwin).

在将这些转换为类模板之前,它们是非泛型的,派生类能够看到基类的静态成员。这是在C ++规范的要求中的可见性的丢失,还是有我需要使用的语法变化?

Prior to converting these to class templates, they were non-generic and the derived class was able to see the base class's static members. Is this loss of visibility in a requirement of the C++ spec or is there a syntax change that I need to employ?

我知道 Base< T> 的每个实例化都有它自己的静态成员 ZEROFILL NO_ZEROFILL Base< float> :: ZEROFILL Base< double> :: ZEROFILL 是不同的变量,但我真的不在乎;常数是为了可读性的代码。我想使用一个静态常量,因为它在名称冲突方面比在宏或全局方面更安全。

I understand that each instantiation of Base<T> will have it's own static member "ZEROFILL" and "NO_ZEROFILL", that Base<float>::ZEROFILL and Base<double>::ZEROFILL are different variables, but i don't really care; the constant is there for readability of the code. I wanted to use a static constant because that is more safe in terms of name conflicts rather than a macro or global.

推荐答案

两相查找。

基本< T> :: NO_ZEROFILL (所有大写识别符都是boo,宏,BTW除外)标识符取决于 T

由于当编译器首次解析模板时,没有实际类型替换 T ,但是编译器不知道什么 Base< T> 是。所以它不能知道你假定要定义的任何标识符(可能有一些特殊的 T ,编译器只能看到),你不能省略基类来自基类中定义的标识符的限定。

Base<T>::NO_ZEROFILL (all caps identifiers are boo, except for macros, BTW) is an identifier that depends on T.
Since, when the compiler first parses the template, there's no actual type substituted for T yet, the compiler doesn't "know" what Base<T> is. So it cannot know any identifiers you assume to be defined in it (there might be a specialization for some Ts that the compiler only sees later) and you cannot omit the base class qualification from identifiers defined in the base class.

这就是为什么你必须写 Base< T> :: NO_ZEROFILL (或 - > NO_ZEROFILL )。这告诉编译器 NO_ZEROFILL 是基类中的某个东西,它依赖于 T ,并且它只能验证它以后,当模板被实例化时。因此,它将接受它,而不尝试验证代码。

该代码只能稍后验证,当模板通过为 T

That's why you have to write Base<T>::NO_ZEROFILL (or this->NO_ZEROFILL). That tells the compiler that NO_ZEROFILL is something in the base class, which depends on T, and that it can only verify it later, when the template is instantiated. It will therefore accept it without trying to verify the code.
That code can only be verified later, when the template is instantiated by supplying an actual parameter for T.

这篇关于为什么派生模板类不能访问基本模板类的标识符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 09:14