using stream operator<< with std::endl in c++

时间秒杀一切 提交于 2020-01-02 07:30:30

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!