我檢查了一塊現有的代碼,發現當用Visual C++ 9和MinGW編譯它的行爲是不同的:比較性病的地址:: ENDL
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<<()
以從流中剝離末端。
我發現,爲什麼它的行爲有所不同:測試p_manip == static_cast...
使用MinGW成功,而失敗的Visual C++ 9
- MinGW的「忽略」的演員和返回
std::endl
真實地址; - Visual C++ 9實際上將指針轉換爲endl並返回不同的地址。
我將測試更改爲if (p_manip == std::endl)
,現在它的行爲如預期。
我的問題是:這樣一個複雜(事實上,錯誤)測試背後的基本原理是什麼?
對於completness的緣故:
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&));
};
您的源代碼控制何時說測試已寫入?這可能是那個時候運算符==()不適用於這些類型。 – Bill 2010-02-23 16:19:55