문제

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