提问人:thor 提问时间:11/22/2017 最后编辑:Hudsonthor 更新时间:3/12/2023 访问量:783
在 C++ 中使用流运算符<< 和 std::endl
using stream operator<< with std::endl in c++
问:
我正在尝试以下C++类,以使用流运算符<<来记录此答案中的内容:
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;
};
这适用于许多情况。但是,它在尝试流式传输时无法编译,std::endl
Log( "/tmp/my.log" ) << 1 << std::endl;
,给出如下错误:
/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;
^~~~
如何让它也一起工作?std:endl
答: 暂无答案
评论
operator<<
std::endl
const T&
std::endl
couldn't deduce template parameter ‘T’
T
T
std::endl
T
log << std::endl<char, std::char_traits<char>>