运算符转换,GCC 和 clang:哪个编译器是正确的

Operator cast, GCC and clang: which compiler is right?

本文关键字:编译器 转换 GCC clang 运算符      更新时间:2023-10-16

请考虑以下代码:

struct S {
    using T = int;
    operator T() { return 42; }
};
int main() {
    S s;
    S::T t = s;
    // Is the following line correct?
    t = s.operator T();
}

它使用 GCC (4.9/5.1/6.1( 编译,但无法使用 clang (3.8/3.7( 编译。
返回的错误是:

错误:未知类型名称"T";您的意思是"S::T"吗?

在这种情况下,哪个编译器是正确的,为什么?

注意

解决它是一个合格的T问题:

t = s.operator S::T();

问题不在于如何使其工作。

我相信这是叮当错误(作为#27807提交(

来自 [basic.lookup.classref]:

如果 id 表达式转换函数 id,则首先在 使用对象表达式和名称(如果找到(。否则,它将在整个上下文中查找 后缀表达式。在每个查找中,仅表示其专用化的类型或模板的名称 是考虑的类型。[ 示例:

struct A { };
namespace N {
    struct A {
        void g() { }
        template <class T> operator T();
    };
}
int main() {
    N::A a;
    a.operator A(); // calls N::A::operator N::A
}

—结束示例 ]

t = s.operator T();中,T首先在S类中查找,它应该找到你的typedef,因此最终调用operator int()