c++ - operator== 使用 msvc 编译,但不使用 gcc 和 clang 编译

标签 c++ operator-overloading language-lawyer function-templates friend-function

我正在使用列出的书籍学习 C++ here 。现在,为了进一步检查我是否理解了这些概念,我还在编写简单的示例程序。下面给出了一个这样的程序,它可以使用 msvc 编译,但不能使用 clang 和 gcc 编译。 Demo .

template<typename P> struct C{
template<typename T>
    struct E
    {
        template<typename U = P, typename V = T>
        friend bool operator==(const typename C<U>::template E<V>&, 
                               const typename C<U>::template E<V>&);
    };
};

int main()
{
    C<int>::E<double> d1, d2;
    
    std::cout<<(d1==d2);      //compiles with msvc but rejected in gcc and clang
}

所以,我的问题是根据标准,哪个编译器就在这里(如果有的话)。

最佳答案

MSVC 接受代码是错误的,因为它格式不正确。这可以从temp.param#12看出其中指出:

If a friend function template declaration specifies a default template-argument, that declaration shall be a definition and shall be the only declaration of the function template in the translation unit.

(强调我的)

由于您提供的友元函数模板声明指定了默认模板参数,而不是定义,因此该程序格式不正确。因此,gcc 和 clang 以及 right 都拒绝了该程序。

要解决此问题,您可以通过添加友元函数模板的主体来提供定义。 Demo .


这是 msvc 错误报告:

Invalid Friend function template operator== compiles with msvc

关于c++ - operator== 使用 msvc 编译,但不使用 gcc 和 clang 编译,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73836226/

相关文章:

c++ - 我可以将 C++17 无捕获 lambda constexpr 转换运算符的结果用作函数指针模板非类型参数吗?

兼容的结构类型

c++ - 将动态分配的二维字符数组传递给函数

c++ - 如何解决这个不明确的模板构造函数调用?

c# - 重载的 false 运算符什么时候被执行,它有什么用?

c++ - 我可以对重载了 operator new 的类使用 global operator new 吗?

java - 从什么时候开始使用运算符 + 进行字符串连接?

c++ - 阈值绝对值

c++ - 我应该使与可调时钟一起工作的成员函数静态化吗?

c++ - 使用 ARM 跨工具链进入同一文件中定义的函数时出现段错误