STL流的包装器类:正向运算符<<来电 [英] wrapper class for STL stream: forward operator<< calls
问题描述
我目前正在为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 int
s and float
s.
是否可以在没有大量自己的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流的包装器类:正向运算符<<来电的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!