开发者

Using member variables inherited from a templated base class (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 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?


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.

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

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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜