【问题标题】:"error: no match for ‘operator<<" when working with std::string“错误:在使用 std::string 时不匹配‘operator<<”
【发布时间】:2012-08-04 18:30:38
【问题描述】:

您能帮我找出以下代码中的问题吗 (代码类似C++ stream as a parameter when overloading 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;
}

在我取消注释包含“世界”的行之前,一切正常。在这种情况下,GCC 产生 错误:'operator 不匹配

有趣的是VS2008对这段代码没有任何问题。

谢谢!

【问题讨论】:

  • Visual Studio 做了很多其他编译器不会做的类型转换。试试 std::string("world").c_str();

标签: c++ string iostream


【解决方案1】:

std::string( "world" ) 创建一个不能绑定到非常量引用的临时对象。将 const 添加到参数中:

template< typename t >
logger& operator <<( t const& data )
{
    *stream << data;
    return *this;
}

编辑:刚刚注意到您提到这在 MSVS 中有效。那是因为 MS 语言扩展,可以关闭它也会显示错误。每当我使用 MSVS 时,我都会关闭语言扩展。

【讨论】:

  • MSVC 已扩展 C++ 以能够进行非const 引用。这解释了编译器之间的差异。可以使用编译器选项禁用此功能,但是有很多 MS 标头无法正常工作。
  • @MagnusHoff 我什至没有注意到那部分,但你是对的。我讨厌那些扩展。
猜你喜欢
  • 2020-10-08
  • 1970-01-01
  • 2014-07-03
  • 1970-01-01
  • 1970-01-01
  • 2012-03-02
  • 2017-11-25
  • 2015-09-09
  • 1970-01-01
相关资源
最近更新 更多