【发布时间】:2013-04-08 04:02:44
【问题描述】:
我有一个名为 Stream 的自定义类
class Stream
public:
Stream& operator<<(int i) { stream_ << i; return *this;}
template <typename CustomClass>
Stream& operator<<(const CustomClass& c) { stream_ << c.toString() /* assume this template always have toString(); return *this; }
private:
std::stringstream stream_;
};
这是我实际拥有的一个非常基本的示例。我正在尝试设置 std::ios_base 标志,如下所示:
Stream() << 1 << std::hex << 2;
使用运算符;
Stream& operator<<(std::ios_base& b) { stream_.setf(b.flags()); return *this; }
据我了解,因为 std::hex 返回 std::ios_base 所以它应该调用它并设置流的标志。但它总是调用模板。注意:如果我删除此模板,一切都会如您所愿,但有没有办法同时拥有这两者?
如果您需要更多说明,请随时进一步询问
【问题讨论】:
-
只是为了澄清一点,我正在尝试使 ios_base 重载运算符 !important 超过模板。我相信这是非常奇怪的行为,因为如果在编译时没有其他类型可以解决,那么模板应该放在最后,应该使用它。我相信 std 库是在所有其他库之前链接的。
-
顺便说一句,即使我返回
std::ios_base&并返回流,这也不起作用,我的意思是它仍然通过类型化重载调用模板
标签: c++ iostream cout flags ostringstream