【发布时间】:2012-02-22 14:12:18
【问题描述】:
#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 );。后者输出1iirc。那么谁对谁错呢?
【问题讨论】:
-
嘿,有什么区别?如果
d << c不能在 MSVC 上编译,那么只有一个1可以打印。其他编译器打印两个1。还是我错过了什么? -
您需要意识到所涉及的任何数据类型都不会有 sizeof == 1: 8 可能,4 肯定,1 为什么不。但是 11 看起来真的很像两个
1。 -
你想要什么?试试编译器?
-
@J.N.
c是<<和sizeof c == 1的参数。如果程序无法编译,则不会打印任何内容。 -
我猜问题是“为什么 MSVC 有编译器错误,而 gcc 没有,这是符合 ISO 的行为吗?”。老实说,我不知道这两个问题的答案。不过祝你好运。
标签: c++ visual-c++ g++ iso icc