質問

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;
}
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top