[英]“error: no match for ‘operator<<” when working with std::string
Could you please help me with finding a problem in the following code (code is similar to C++ stream as a parameter when overloading operator<< ): 你可以帮我找到下面代码中的问题(代码类似于C ++流作为重载operator <<时的参数 ):
#include <iostream>
#include <string>
class logger
{
public:
void init( std::ostream& ostr )
{
stream = &ostr;
}
template< typename t >
logger& operator <<( t& data )
{
*stream << data;
return *this;
}
logger& operator <<( std::ostream& (*manip)(std::ostream &) )
{
manip( *stream );
return *this;
}
logger& operator <<( std::ios_base& (*manip)(std::ios_base&) )
{
manip( *stream );
return *this;
}
private:
std::ostream* stream;
};
int main( int argc, char* argv[] )
{
logger log;
log.init( std::cout );
log << "Hello" << std::endl;
//log << std::string( "world" ) << std::endl;
return 0;
}
Everything works fine until I uncomment the line containing "world". 一切正常,直到我取消注释包含“世界”的行。 In this case, GCC produces error: no match for 'operator<<' in ...
在这种情况下,GCC产生错误:在......中没有匹配'operator <<'
It is interesting that VS2008 has no problem with this code. 有趣的是,VS2008对此代码没有任何问题。
Thank you! 谢谢!
std::string( "world" )
creates a temporary which can't bind to a non-const reference. std::string( "world" )
创建一个不能绑定到非const引用的临时表。 Add const to the parameters: 将const添加到参数:
template< typename t >
logger& operator <<( t const& data )
{
*stream << data;
return *this;
}
EDIT: Just noticed that you mentioned this works in MSVS. 编辑:刚刚注意到你提到这在MSVS中有效。 That's because of MS language extensions, which can be turned off and it too will show de error.
这是因为MS语言扩展,可以关闭,它也会显示de error。 Whenever I use MSVS I turn off language extensions.
每当我使用MSVS时,我都会关闭语言扩展。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.