[英]Is possible to get automatic cast from user-defined type to std::string using cout?
[英]Why cannot use cout with user-defined conversion to std::string?
在這里,我定義一個Date
,並指定一個用戶定義的轉換。
class Date {
private:
int day;
int month;
string dateStr;
public:
Date(int _day, int _month) : day(_day), month(_month) {}
operator const string() {
ostringstream formattedDate;
formattedDate << month << "/" << day;
dateStr = formattedDate.str();
return dateStr;
}
};
轉換為string
時效果很好。
Date d(1, 1);
string s = d;
但是為什么不能直接與cout
一起使用呢?
cout << d << endl; // The compiler complains that there is no suitable type marching << operator
但是,如果我使用char*
而不是string
進行用戶定義的轉換,則可以直接將其與cout
一起使用。 為什么?
operator const char*() {
ostringstream formattedDate;
formattedDate << month << " / " << day;
dateStr = formattedDate.str();
return dateStr.c_str();
}
PS。 我知道直接<<
重載將很好地用於輸出。 但是我的問題是: 為什么不能將<<
和用戶定義的轉換一起使用到std::string
?
需要注意的是std::string
是模板實例化std::basic_string
, 簽名operator<<
對std::string
確實是:
template <class CharT, class Traits, class Allocator>
std::basic_ostream<CharT, Traits>&
operator<<(std::basic_ostream<CharT, Traits>& os,
const std::basic_string<CharT, Traits, Allocator>& str);
然后為cout << d;
,必須推導std::basic_string
的模板參數; 但是類型推導不考慮隱式轉換 ;
類型推導不考慮隱式轉換(上面列出的類型調整除外):這是超載解析的工作,稍后會發生。
這意味着扣除將失敗; 那么沒有候選函數是可行的。
但是operator<<
for const char*
並沒有這種問題; 隱式轉換生效,然后正常工作。
要解決此問題,可以使用顯式轉換來避免模板參數的推導。 或直接在Date
類型上重載operator<<
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.