operator overloading << for enum to ostringstream

5k views Asked by At

I have the following macro.

#define STRING_STREAM( data )       \
    ( ( (std::ostringstream&)       \
        ( std::ostringstream( ).seekp( 0, std::ios_base::cur ) << data ) ).str( ) )

I am trying to overload << for an enum:

std::ostringstream& operator<<( std::ostringstream& oStrStream, TestEnum& testEnum )
{
    oStrStream << "TestEnum";
    return oStrStream;
}

When I call STRING_STREAM( testEnum ), it doesn't use the overloaded <<. It prints enums number value.

2

There are 2 answers

1
ssk On BEST ANSWER
std::ostream& operator<<( std::ostream& oStrStream, const TestEnum testEnum )
{
    oStrStream << "TestEnum";
    return oStrStream;
}
4
Jared Sealey On

The problem is that the overloaded << operator is expecting an argument of..

new ostringstream() 

but you're giving it the argument..

ostringstream()

This is not being matched by the overloaded function.

In my example, I used auto_ptr to automatically deallocate the ostringstream after it goes out of scope. This allows us to use a macro to perform our function without memory leaks.

#include<sstream>
#include<iostream>
#define STRING_STREAM( data )                                                  \
   ((ostringstream&)( *( auto_ptr<ostringstream>(new ostringstream()) ) << data)).str()

using namespace std;

enum TestEnum { ALPHA, BETA };

ostringstream& operator<<( ostringstream& oss, TestEnum testEnum ){
    oss << "TestEnum";
    return oss;
}
int main(){
    cout << STRING_STREAM( ALPHA ) << endl;
}