"error: no match for" operator << "when working with std :: string

Could you please help me find the problem in the following code (the code looks like a C ++ stream as a parameter in the overload operation << ;

#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 the "world". In this case, GCC produces an error: there is no match for 'operator <<<in ...

Interestingly, VS2008 has no problems with this code.

Thank!

+5
source share
1 answer

std::string( "world" )creates a temporary one that cannot communicate with a non-constant link. Add a constant to the parameters:

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

EDIT: , MSVS. - MS, , . , MSVS, .

+12

All Articles