gpt4 book ai didi

c++ - 以下代码的符合 ISO C++ 标准的结果

转载 作者:行者123 更新时间:2023-11-30 03:03:24 24 4
gpt4 key购买 nike

#include <iostream>

template< typename U >
struct base {
template< typename T >
base const & operator<<( T x ) const {
std::cout << sizeof( x ) << std::flush;
return *this;
}
};

template< typename U >
struct derived : public base< U > {
using base<U>::operator<<;

derived const & operator<<( float const & x ) const {
std::cout << "derived" << std::flush;
return *this;
}
};

int main() {
unsigned char c( 3 );
derived< double > d;
d << c;
d.operator<<( c );
return 0;
}

能否请您解释一下获得上述代码正确答案所涉及的规则(与模板相关的重载和覆盖,积分提升,...)?有效吗?如果规则太长,请提供文献引用。最新的编译器不同意正确的结果。 gcc-4.6 和 icpc-12.1.0 声称“11”是正确答案,但 VS2010 拒绝编译 d << c;由于含糊不清,但接受 d.operator<<( c ); .后者输出 1 IIRC。那么谁对谁错呢?

最佳答案

“11”是正确的输出。

对于这两个表达式,派生运算符<< 和基本运算符<< 都是候选者。然后根据候选者所需的隐式转换序列对候选者进行比较。因为基本运算符 << 是一个模板函数,其中类型 T 已被推导出来匹配参数,所以在这两种情况下它都是更好的匹配。

确切的规则很长。您可以在当前 C++ 标准草案的第 13.3 部分重载解决方案中找到详细信息,n3337 链接到 this list工作组的论文。

如果你问为什么 MSVC 不编译一个语句,我不太确定,但是当有多个计算的 ICS 并不比彼此更好时(如 13.3.1 中所定义),函数调用是不明确的。 3).在 d << c 的情况下,MSVC 似乎至少为其中一个重载计算了错误的 ICS ,但诊断没有提供更多详细信息:

error C2666: 'derived<U>::operator <<' : 2 overloads have similar conversions
with
[
U=double
]
ConsoleApplication1.cpp(24): could be 'const derived<U> &derived<U>::operator <<(const float &) const'
with
[
U=double
]
ConsoleApplication1.cpp(14): or 'const base<U> &base<U>::operator <<<unsigned char>(T) const'
with
[
U=double,
T=unsigned char
]
while trying to match the argument list '(derived<U>, unsigned char)'
with
[
U=double
]

关于c++ - 以下代码的符合 ISO C++ 标准的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9396470/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com