5

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!

Community
  • 1
  • 1
Serge C
  • 2,205
  • 16
  • 23
  • Visual studio does a lot of type conversion that other compilers won't do. Try std::string( "world" ).c_str(); – steveg89 Aug 07 '12 at 17:35

1 Answers1

12

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.

Luchian Grigore
  • 253,575
  • 64
  • 457
  • 625
  • 2
    MSVC has extended C++ to be able to make non-`const` references. This explains the discrepancy between the compilers. It is possible to disable this with a compiler option, but then there's lots of MS headers that won't work. – Magnus Hoff Aug 07 '12 at 17:36
  • @MagnusHoff I didn't even notice that part, but you're right. I hate those extensions. – Luchian Grigore Aug 07 '12 at 17:39