Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 548
The Unknown Avatar asked May 05 '09 02:05

The Unknown


3 Answers

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.

like image 200
Evan Teran Avatar answered Nov 12 '22 17:11

Evan Teran


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

like image 1
bdonlan Avatar answered Nov 12 '22 17:11

bdonlan


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);
}
like image 1
Martin York Avatar answered Nov 12 '22 17:11

Martin York