[英]Cannot std::cout an implicitly converted std::string
我曾經通過std::cout << str << std::endl
顯示字符串,並認為 object 隱式轉換為std::string
也可以以這種方式顯示。
然而,我注意到我錯了。 在我為 std::string 重載operator <<
之前,我無法std::cout
隱式轉換的std::string
::string。
以下代碼演示了上述內容。
#include <stdio.h>
#include <iostream>
#include <string>
class X
{
public:
operator std::string() const {
return std::string("world");
}
};
#ifdef OVERLOAD_STREAM_OP
std::ostream& operator<<(std::ostream& os, const std::string& s) {
return os << s;
}
#endif
int main() {
std::string s = "hello";
std::cout << s << std::endl; // viable
printf("---\n");
X x;
std::cout << x << std::endl; // not viable
return 0;
}
看來,在 STL 實現中,std::string 類型的重載operator <<
function 有點不同(但我真的不明白那些模板的東西):
template<typename _CharT, typename _Traits, typename _Allocator>
std::basic_ostream<_CharT, _Traits>&
operator<<(std::basic_ostream<_CharT, _Traits>& __os,
const basic_string<_CharT, _Traits, _Allocator>& __str)
{ return __os << __str._M_base(); }
我的問題:
STL 的重載operator <<
和我自己的std::string
類型的重載operator<<
符 << 有什么區別?
為什么我不能用std::cout
顯示隱式轉換的 std::string object x
(編譯錯誤)?
- STL 的重載
operator <<
和我自己的 std::string 類型的重載operator<<
符 << 有什么區別?
您的operator<<
是非模板,而 STL 的一個是模板。
- 為什么我不能用
std::cout
顯示隱式轉換的std::string
object x (編譯錯誤)?
模板參數推導中不會考慮隱式轉換(從X
到std::string
),這會導致對模板operator<<
的調用失敗。 另一方面,非模板operator<<
沒有這樣的問題。
類型推導不考慮隱式轉換(除了上面列出的類型調整):這是重載解析的工作,稍后會發生。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.