我正在检查一段现有代码,发现它在使用 Visual C++ 9 和 MinGW 编译时表现不同:
inline LogMsg& LogMsg::operator<<(std::ostream& (*p_manip)(std::ostream&) )
{
if ( p_manip == static_cast< std::ostream& (*)(std::ostream&) > ( &std::endl<char, std::char_traits<char> >) )
{
msg(m_output.str());
m_output.str( "" );
}
else
{
(*p_manip) (m_output); // or // output << p_manip;
}
return *this;
}
顾名思义,这是一个日志类,它重载了operator<<()
。从流中剥离 endls。
我发现了它行为不同的原因:测试 p_manip == static_cast...
MinGW 成功,而 Visual C++ 9 失败。
- MinGW“忽略”转换并返回
std::endl
的真实地址; - Visual C++ 9 实际上转换指针到 endl 并返回不同的地址。
我把测试改为if ( p_manip == std::endl )
现在它的行为符合预期。
我的问题是:如此复杂(实际上是错误的)测试背后的基本原理是什么?
为了完整起见:
class LogStream
{
public:
LogStream() {}
protected:
std::ostringstream m_output;
};
class LogMsg : public LogStream
{
friend LogMsg& msg() ;
static LogMsg s_stream;
public:
LogMsg() {}
template <typename T>
inline LogMsg& operator<<(T p_data);
inline LogMsg& operator<<(std::ostream& (*p_manip)(std::ostream&) );
};
最佳答案
我猜,我会说原作者没有意识到它们是兼容的类型,并按照规范进行了转换(编译器没有要求他这样做)。
关于c++ - 比较 std::endl 的地址,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2319544/