Shell class for STL stream: direct operator << calls

I am currently writing a wrapper for an STL thread to synchronize write calls from multiple threads. I have the following (simplified) code:

class Synchronize {
private:
    std::stringstream ss;
public:
    void write(std::string& str) {
        // locking ...
        ss << str;
        // unlocking ...
    };

    // other stuff ..
};

Synchronize& operator<<(Synchronize& o, std::string& str) {
    o.write(str);
    return o;
}

Synchronize& operator<<(Synchronize* o, std::string& str) {
    o->write(str);
    return *o;
}

Now you can call the method write()using the operator <<for the class object Synchronize, but only with std::string. And std::stringstreamalso it takes a lot of other things, such as intand floats.

Is it possible to add this functionality to my class Synchronizewithout a ton of native functions operator<<? Would templates help? Or do I need to extend a class from a library iostream?

+1
source share
2

template<typename T>
friend Synchronize& operator<<(Synchronize& o, T const& t);

template<typename T>
Synchronize& operator<<(Synchronize& o, T const& t) {
    o.write(t);
    return o;
}

 //edit
template<typename T>
void Synchronize::write(T& t)
{
    ss << t;
}
+3

, , . ( std:: stream / ) .

, , :

Synchronize your_stream;

void thread_function1()
{
    output << "this is a message " << "from thread_function1\n";
}
void thread_function2()
{
    output << "this is a message " << "from thread_function2\n";
}

:

this is a message this is a message from thread_function2
from thread_function1

- / :

your_stream  out;
out << synchronize_begin << "this is " << " a test" << synchronize_end;

( synchronize_begin ( ), synchronize_end, mutex ( synchronize_begin) out).

std::ostream  out; // any std::ostream type
out << synchronized << "this is " << " a test"; // synchronized ends here

( - , , , , .

0

All Articles