views:

727

answers:

3

I have a C++ class MyObject and I want to be able to feed this data like I would to a osstream (but unlike a direct sstream, have the incoming data be formatted a special way). I can't seem to figure out how to overload a operator for MyObject to eat input given to it.

class MyObject {
public:
    ostringstream s;
    FEEDME
};


int main() {
     MyObject obj;
     obj.FEEDME << "Hello" << 12345;

     // I want obj.s == ":Hello::12345:"

}

I want it so every item fed in be surrounded by : :

So in the given example, s = ":Hello::12345" should be the final outcome. What my question is, how can I tell the object that when ever a <<something, put : : around the something.

Is this possible?

A: 

You may find the answers for http://stackoverflow.com/questions/524641/how-do-i-create-an-ostream-streambuf helpful.

bdonlan
+5  A: 

try this:

class MyObject {
public:
    template <class T>
    MyObject &operator<<(const T &x) {
        s << ':' << x << ':';
        return *this;
    }

    std::string to_string() const { return s.str(); }

private:
    std::ostringstream s;
};

MyObject obj;
obj << "Hello" << 12345;
std::cout << obj.to_string() << std::endl;

There are certain things you won't be able to shove into the stream, but it should work for all the basics.

Evan Teran
The Unknown
I think that compiles fine in g++ 4.3.3, what compiler are using?
Evan Teran
g++ (GCC) 4.3.2, you are correct it compiles and works exactly like I want it to! Thank you. The problem seems to be something particular to my program.
The Unknown
+1  A: 

I would take a slightly different approach and create a formater object.
The formater object would then handle the inserting of format character when it is applied to a stream.

#include <iostream>

template<typename T>
class Format
{
    public:
        Format(T const& d):m_data(d)    {}
    private:
        template<typename Y>
        friend std::ostream& operator<<(std::ostream& str,Format<Y> const& data);
        T const&    m_data;
};
template<typename T>
Format<T> make_Format(T const& data)    {return Format<T>(data);}

template<typename T>
std::ostream& operator<<(std::ostream& str,Format<T> const& data)
{
    str << ":" << data.m_data << ":";
}




int main()
{
    std::cout << make_Format("Hello") << make_Format(123);
}
Martin York