c++ - Overloading operator<< for endl using templates -
i have class inherits ofstream
. want overload insertion operator can drop in repalcement ofstream.
the first overload is
template<class t> myclass& myclass::operator<<(const t& in);
and try , handle manipulators std::endl
template< template<class, class> class outer, class inner1, class inner2 > myclass& myclass::operator<<(outer<inner1, inner2>& (*foo)(outer<inner1, inner2>&));
if try compile with:
myclass output; output << 3 << "hi";
then works fine, when try add std::endl
myclass output; output << 3 << "hi" << std::endl; temp.cpp: in function 'int main()': temp.cpp:10: error: no match 'operator<<' in '((stream*)ss. stream::operator<< [with t = int](((const int&)((const int*)(&3)))))->stream::operator<< [with t = char [3]](((const char (&)[3])"hi")) << std::endl' /usr/include/c++/4.1.2/bits/ostream.tcc:657: note: candidates are: std::basic_ostream<_chart, _traits>& std::operator<<(std::basic_ostream<_chart, _traits>&, const _chart*) [with _chart = char, _traits = std::char_traits<char>] /usr/include/c++/4.1.2/bits/ostream.tcc:597: note: std::basic_ostream<_chart, _traits>& std::operator<<(std::basic_ostream<_chart, _traits>&, _chart) [with _chart = char, _traits = std::char_traits<char>]
i don't understand why in error printout there const int*
. attempt learn more templates, trying cover more manipulators single piece of code.
edit sscce:
#include <fstream> #include <iostream> class myclass : public std::ofstream { //class stream { private: public: template<class t> myclass& operator<<(const t& data_in) { std::cout << data_in; return *this; } template< template<class, class> class outer_t, class inner_t1, class inner_t2 > myclass& operator<<(outer_t<inner_t1, inner_t2>& (*foo)(outer_t<inner_t1, inner_t2>&)) { return foo(*this); } }; int main() { myclass output; output << 3 << "hi"; output << 3 << "hi" << std::endl; }
don't try it. overloading of operator<<
, operator>>
iostream types complicated , messy.
what should instead create own std::streambuf
subclass, , arrange standard stream class use that. way can override happens character stream data, without worrying overloaded operators, type conversion, formatting, , manipulators. example, see james kanze's filtering streambufs article, or boost library boost::iostreams
.
Comments
Post a Comment