Thursday, May 5, 2011

Have a C++ Class act like a custom ostream, sstream

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?

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

  • 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.

    The Unknown : 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.
    Evan Teran : I think that compiles fine in g++ 4.3.3, what compiler are using?
    The Unknown : 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.
  • 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);
    }
    

0 comments:

Post a Comment

Note: Only a member of this blog may post a comment.