1

現在、複数のスレッドからの書き込み呼び出しを同期するための STL ストリームのラッパーを作成しています。次の(簡略化された)コードがあります。

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;
}

クラスのオブジェクトで演算子をwrite()使用してメソッドを呼び出すことができるようになりましたが、 . また、 s やsなど、他の多くのものも必要です。<<Synchronizestd::stringstd::stringstreamintfloat

Synchronize独自の関数を大量に使用せずに、この機能をクラスに追加することは可能operator<<ですか? テンプレートは役に立ちますか?iostreamまたは、ライブラリからいくつかのクラスを拡張する必要がありますか?

4

2 に答える 2

3

オペレーターのオーバーロードをフレンド テンプレートに変えることができます

クラスの中で書く

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;
}
于 2013-02-07T13:42:54.247 に答える
0

私の理解が正しければ、多くの読者を 1 つの宛先に配置する必要があります。作成したアーキテクチャ (同期/ロックされた書き込みを行う 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ロックして に書き込みます)。mutexsynchronize_beginout

また:

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

(synchronized は、行の最後でスコープを終了するバッファー インスタンスです。それが out に書き込まれると、ロックされてから、そのデータが書き込まれます。

于 2013-02-07T14:22:20.810 に答える