當重載operator <<時,std :: endl是未知類型我重載了運算符<<template <Typename T>UIStream& operator<<(const T);UIStream my_stream;my_stream << 10 << " heads";工作但是:my_stream << endl;給出編譯錯誤:錯誤C2678:二進制'<<':找不到哪個運算符帶有'UIStream'類型的左操作數(shù)(或者沒有可接受的轉(zhuǎn)換)做my_stream << endl工作的工作是什么?
3 回答

汪汪一只貓
TA貢獻1898條經(jīng)驗 獲得超8個贊
std::endl
是一個函數(shù),std::cout
通過實現(xiàn)operator<<
獲取具有相同簽名的函數(shù)指針來利用它std::endl
。
在那里,它調(diào)用函數(shù),并轉(zhuǎn)發(fā)返回值。
這是一個代碼示例:
#include <iostream>struct MyStream{ template <typename T> MyStream& operator<<(const T& x) { std::cout << x; return *this; } // function that takes a custom stream, and returns it typedef MyStream& (*MyStreamManipulator)(MyStream&); // take in a function with the custom signature MyStream& operator<<(MyStreamManipulator manip) { // call the function, and return it's value return manip(*this); } // define the custom endl for this stream. // note how it matches the `MyStreamManipulator` // function signature static MyStream& endl(MyStream& stream) { // print a new line std::cout << std::endl; // do other stuff with the stream // std::cout, for example, will flush the stream stream << "Called MyStream::endl!" << std::endl; return stream; } // this is the type of std::cout typedef std::basic_ostream<char, std::char_traits<char> > CoutType; // this is the function signature of std::endl typedef CoutType& (*StandardEndLine)(CoutType&); // define an operator<< to take in std::endl MyStream& operator<<(StandardEndLine manip) { // call the function, but we cannot return it's value manip(std::cout); return *this; }};int main(void){ MyStream stream; stream << 10 << " faces."; stream << MyStream::endl; stream << std::endl; return 0;}
希望這能讓您更好地了解這些事情是如何運作的。

白板的微信
TA貢獻1883條經(jīng)驗 獲得超3個贊
問題是這std::endl
是一個功能模板,就像你的運營商一樣<<
。所以當你寫:
my_stream << endl;
你會希望編譯器為運算符推導出模板參數(shù)endl
。這是不可能的。
因此,您必須編寫額外的非模板,操作符重載<<
以使用操縱器。他們的原型看起來像:
UIStream& operator<<(UIStream& os, std::ostream& (*pf)(std::ostream&));
(還有另外兩個,替換std::ostream
為std::basic_ios<char>
和 std::ios_base
,如果你想允許所有的操縱器你也必須提供),它們的實現(xiàn)將與你的模板非常相似。實際上,如此相似,您可以使用您的模板進行實現(xiàn),如下所示:
typedef std::ostream& (*ostream_manipulator)(std::ostream&);UIStream& operator<<(UIStream& os, ostream_manipulator pf){ return operator<< <ostream_manipulator> (os, pf);}
最后一點,通常是編寫自定義streambuf
通常是一種更好的方法來實現(xiàn)應用于您正在使用的技術。
- 3 回答
- 0 關注
- 977 瀏覽
添加回答
舉報
0/150
提交
取消