簡體   English   中英

std :: ostream :: operator <<沒有為std :: string定義?

[英]std::ostream::operator<< not defined for std::string?

我偶然發現了一個我無法理解的錯誤。

我認為它基本上歸結為這個錯誤:

 error: no matching function for call to ‘std::basic_ostream<char>::operator<<(const std::basic_string<char>&)’

我查看了www.cplusplus.com上的規范 ,實際上它說沒有std::ostream::operator<<定義, std::string作為參數。

我的問題是,當寫一個std_ostream_instance << std_fancy_string; 我相信它是const char*旁邊最常見的調用之一(例如std::out << std::string("Hello world!") )。

錯誤源自以下行:

template<typename T> 
void Log::_log(const T& msg)
{  _sink->operator<<( msg ); }

_sink被定義為std::ostream*有一些包裝函數,但它在這里打破。

我想我可以通過寫作來解決

template<> 
void Log::_log<std::string>(const std::string& msg) {
  _sink->operator<<( msg.c_str() );
}

因為有ostream& operator<< (ostream& out, const unsigned char* s ); 默認定義。

我沒有看到沒有理由為什么它沒有自動猜測,因為它顯然可以像cout << any_std_string一樣簡單使用。

不確定這是否相關但我希望能夠通過我的日志函數向下傳遞std::ostream可以處理的任何內容。 我使用了顯式的非模板化聲明,但決定轉到log(const T& anything_to_log)模板來重新設計它。 擁有5+超載似乎很愚蠢。 當我嘗試編譯Log::log( std::string("test case") )類的東西時,我收到錯誤。

它看起來像一些愚蠢的簡單但我不能靠自己得到它。 試圖谷歌和搜索堆棧無濟於事。

關於,luk32。

PS。 我檢查了解決方法並且它有效。 為什么它沒有隱含地完成?

operator << overloads不是ostream成員。 例如,它們是獨立的功能

ostream& operator << ( ostream& out, const basic_string<T>& bs );

嘗試

template<typename T> 
void Log::_log(const T& msg)
{  *_sink << msg;  }

std::string版本不是成員函數,因此不能作為_sink的成員_sink 嘗試這種方式來獲取成員和非成員版本(實際上你根本不需要成員版本):

#include <iostream>
#include <string>

int main()
{
    std::ostream * os = &std::cout;
    std::string s = "Hello\n";

    // This will not work
    // os->operator<<(s);
    (*os) << s;

    return 0;
}

或者更好的是將_sink存儲為參考,並按照通常的cout輸出。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM