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!
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With