我正在使用列出的书籍学习 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/