8

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?

Logan Capaldo
  • 39,555
  • 5
  • 63
  • 78
The Unknown
  • 19,224
  • 29
  • 77
  • 93

3 Answers3

10

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
  • 87,561
  • 32
  • 179
  • 238
  • Thanks, I think I have footing on how to implement it now, still getting a error "error: invalid use of member (did you forget the ‘&’ ?)" for MyObject &operator<<(const T &x) { But will mess with it and get resolved. Thank you good sir. – The Unknown May 05 '09 at 02:30
  • I think that compiles fine in g++ 4.3.3, what compiler are using? – Evan Teran May 05 '09 at 02:33
  • 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 May 05 '09 at 02:56
1

You may find the answers for How do I create my own ostream/streambuf? helpful.

Community
  • 1
  • 1
bdonlan
  • 224,562
  • 31
  • 268
  • 324
1

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
  • 257,169
  • 86
  • 333
  • 562