问题
I am trying out the following C++ class for using the stream operator << to log contents from this answer:
class Log
{
public:
Log()
: m_filename( "dafault.log" )
{}
// if you wanna give other names eventually...
Log( const std::string & p_filename )
: m_filename( p_filename )
{}
virtual ~Log()
{
// implement your writeToFile() with std::ofstream
writeToFile( m_filename, m_stream, true );
}
template< typename T >
Log & operator<<( const T & p_value )
{
m_stream << p_value;
return *this;
}
private:
std::string m_filename;
std::ostringstream m_stream;
};
This works for many cases. However, it fails to compile when trying to stream std::endl
,
Log( "/tmp/my.log" ) << 1 << std::endl;
, giving an error like this:
/usr/include/c++/7/string_view:558:5: note: template argument deduction/substitution failed:
My.cpp:375:36: note: 'Log' is not derived from 'std::basic_ostream<_CharT, _Traits>'
Log( "/tmp/my.log" ) << 1 << std::endl;
^~~~
How to make it work with std:endl
as well?
来源:https://stackoverflow.com/questions/47427695/using-stream-operator-with-stdendl-in-c