简体   繁体   English

使用别名作为 scope 获取父成员时的不同编译器行为

[英]Different compiler behaviour when using alias as scope to get parent member

This code compiles fine on Clang and Visual C++ but not on GCC:此代码在 Clang 和 Visual C++ 上编译良好,但在 GCC 上编译良好:

#include <iostream>


template <class T>
struct Test {
    Test(T &t) : _t(t) {
    }
    
    void method() {
        std::cout << _t.Internal::_value << "\n";       // Doesn't work on GCC
        std::cout << _t.T::Internal::_value << "\n";    // Work on all compilers
    }

private:
    T &_t;
};

template <class T>
struct Base {
    T _value = 1;
};

template <class T>
struct Child : Base<int> {
    using Internal = Base<int>;
    
    int _value = 2;
};

int main(int argc, const char * argv[]) {
    Child<float> child;
    Test<Child<float>> test(child);
    
    test.method();
    
    return 0;
}

The error message from GCC is来自 GCC 的错误消息是

error: 'Internal' has not been declared
    9 |         std::cout << _t.Internal::_value << "\n";
      |                         ^~~~~~~~

Which one is right?哪一个是对的?

Visual C++ and Clang are right in accepting this code. Visual C++ 和 Clang 正确接受此代码。

It was a bug in GCC that prevented it from doing the same.这是 GCC 中的一个错误,它阻止了它做同样的事情。 The error as in the question was up to GCC 10, in GCC 11 its wording changed to问题中的错误高达 GCC 10,在 GCC 11 中,其措辞更改为

error: request for member 'Internal' in non-class type 'T'
    9 |         std::cout << _t.Internal::_value << "\n";
      |                         ^~~~~~~~

And GCC trunk finally accepts the code as well.并且 GCC 中继最终也接受了代码。 Demo: https://gcc.godbolt.org/z/dj34Yhns3演示: https://gcc.godbolt.org/z/dj34Yhns3

So we could expect the fix in GCC 12.所以我们可以期待 GCC 12 中的修复。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 访问基本 class 的受保护成员时,相同的层次结构,不同的行为 - Same hierarchy, different behaviour when accessing protected member of base class 成员函数重载决议涉及“使用”别名的英特尔C ++编译器错误? - Intel C++ compiler bug in member function overload resolution involving “using” alias? 我可以使用相同的名称为周围范围内的类型声明一个成员类型别名吗? - May I declare a member type alias to a type in a surrounding scope, using the same name? “使用”类范围的类型别名:[何时] 方法中的用法可以先于类型别名吗? - "using" type alias of class scope: [when] can usages in methods PRECEDE the type alias? 使用带编译器优化的std :: function类成员时的Segfault - Segfault when using std::function class member with compiler optimizations 成员在不同名称空间中的别名声明专门化 - Member specialization of alias declaration in different namespaces 获取父结构的成员 - Get member of parent struct 编译器什么时候需要计算别名? - When does the compiler need to compute an alias? 使用公共成员函数访问私有成员变量时出错:变量“未在此范围内声明” - Error when using public member function to access private member variable: Variable “was not declared in this scope” 如何通过范围解析操作员获取类成员的地址时使用指针到成员? - How Does Getting the Address of a Class Member Through a Scope Resolution Operator Work When Using a Pointer-to-Member?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM