【问题标题】:Using member variables inherited from a templated base class (C++)使用从模板化基类 (C++) 继承的成员变量
【发布时间】:2010-04-29 16:24:23
【问题描述】:

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

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 中的错误?

【问题讨论】:

标签: c++ inheritance templates compiler-construction


【解决方案1】:

您可能在 icc 中以非严格模式编译。无论如何,由于x 是不合格的,因此不应在任何依赖于模板参数的基类中查找它。所以在你的代码中,没有找到x的地方,你的代码是无效的。

使用另一种形式的查找(类成员访问查找和限定查找)查找其他名称。如果可以,这两种形式都会查看依赖的基类(即它们是否是依赖的,因此在知道dtype 时实例化模板时会查找它们 - 所有其他名称都依赖于模板参数)。

即使是最新版本的 GCC 也没有正确实现,并且在非限定查找期间某些依赖名称 still resolve against dependent bases

【讨论】:

    猜你喜欢
    • 2016-12-03
    • 1970-01-01
    • 1970-01-01
    • 2018-11-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-09
    • 1970-01-01
    相关资源
    最近更新 更多