简体   繁体   中英

operator overloading << for enum to ostringstream

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.

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

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM