比较 std::endl 的地址
-
22-09-2019 - |
题
我正在检查一段现有代码,发现使用 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&) );
};
解决方案 2
欲了解更多信息:
该声明 if ( p_manip == std::endl )
无法在原始编译器(gcc 3.4.5,最初开发代码的编译器)上进行编译。
这意味着测试没有错误,正如我在问题中所说的那样。
其他提示
据猜测,我想说原作者没有意识到它们是兼容的类型,并且按照规范进行了转换(编译器没有要求他这样做)。
不隶属于 StackOverflow