Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"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<<):

#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 ...

It is interesting that VS2008 has no problem with this code.

Thank you!

like image 999
Serge C Avatar asked Aug 07 '12 17:08

Serge C


1 Answers

std::string( "world" ) creates a temporary which can't bind to a non-const reference. Add const to the parameters:

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

EDIT: Just noticed that you mentioned this works in MSVS. That's because of MS language extensions, which can be turned off and it too will show de error. Whenever I use MSVS I turn off language extensions.

like image 176
Luchian Grigore Avatar answered Oct 04 '22 00:10

Luchian Grigore