STL流的包装器类:正向运算符<<来电 [英] wrapper class for STL stream: forward operator<< calls

查看:83
本文介绍了STL流的包装器类:正向运算符<<来电的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在为STL流编写包装器,以同步来自多个线程的写调用.我有以下(简化)代码:

I'm currently writing a wrapper for STL stream 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;
}

现在可以通过对Synchronize类的对象使用<<运算符来调用write()方法,但只能使用std::string.而且std::stringstream还需要很多其他内容,例如int s和float s.

Its now possible to call the write() method by using the << operator on an object of the Synchronize class, but only by using a std::string. And std::stringstream also takes a lot of other stuff like ints and floats.

是否可以在没有大量自己的operator<<函数的情况下将此功能添加到我的Synchronize类中?模板会有所帮助吗?还是应该从iostream库中扩展一些类?

Is it possible to add this functionality to my Synchronize class without a ton of own operator<< functions? Would templates help? Or should I extend some class from the iostream library?

推荐答案

您可以将运算符重载转换为朋友模板

You can turn your operator overload into a friend template

在课堂上写

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

这篇关于STL流的包装器类:正向运算符&lt;&lt;来电的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆