使用从模板化基类(C ++)继承的成员变量 [英] Using member variables inherited from a templated base class (C++)

查看:75
本文介绍了使用从模板化基类(C ++)继承的成员变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在派生类中使用模板化基类的成员变量,如本例所示:

I'm trying to use member variables of a templated base class in a derived class, as in this example:

template <class dtype>
struct A {
    int x;
};

template <class dtype>
struct B : public A<dtype> {
    void test() {
        int id1 = this->x;      // always works
        int id2 = A<dtype>::x;  // always works
        int id3 = B::x;         // always works
        int id4 = x;            // fails in gcc & clang, works in icc and xlc
    }
};

gcc和clang对于使用此变量都非常挑剔,并且需要显式范围或显式使用 this。使用其他一些编译器(xlc和icc),事情按我期望的那样工作。这是xlc和icc允许的非标准代码,还是gcc和clang中的错误?

gcc and clang are both very picky about using this variable, and require either an explicit scope or the explicit use of "this". With some other compilers (xlc and icc), things work as I would expect. Is this a case of xlc and icc allowing code that's not standard, or a bug in gcc and clang?

推荐答案

在icc中以非严格模式进行编译。无论如何,由于 x 是不合格的,因此不应在依赖于模板参数的任何基类中对其进行查找。因此,在您的代码中,找不到 x 的位置,并且您的代码无效。

You are probably compiling in non-strict mode in icc. Anyway, since x is unqualified, it shall not be looked up in any base classes that depend on the template parameters. So in your code, there is no place where x is found, and your code is invalid.

使用其他形式的查找(类成员访问查找和限定查找)查找其他名称。如果可以的话,这两种形式都将查找依赖的基类(即,如果它们是依赖的,并且因此在已知 dtype 时实例化模板时进行查找-所有其他形式名称取决于模板参数)。

The other names are looked up using another form of lookup (class member access lookup, and qualified lookup). Both of those forms will look into dependent base classes if they can (i.e if they are dependent, and are thus looked up when instantiating the template when dtype is known - all your other names are dependent on template parameters).

即使在最新版本的GCC中也无法正确实现该功能,并且某些从属名称在不合格的查找过程中仍会针对依存碱基进行解析

Even GCC in their latest versions don't implement that correctly, and some dependent names still resolve against dependent bases during unqualified lookup.

这篇关于使用从模板化基类(C ++)继承的成员变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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