考虑这个例子:
#include <sstream>
#include <ctime>
using MyStream = std::stringstream;
struct MyTime
{
explicit MyTime(std::time_t time) // w/o explicit the MyTime operator << is ambigous as well
{
}
};
/*
having this overload of course solves everything, but that seems wrong
std::stringstream &operator<<(std::stringstream &stream, char c)
{
stream.put(c);
return stream;
}
*/
MyStream& operator<<(MyStream &stream, std::time_t time)
{
return stream;
}
MyStream& operator<<(MyStream &stream, const MyTime &time)
{
return stream;
}
int main(int argc, char **argv)
{
MyStream stream;
stream << 'Z';
return 0;
}
在没有std::stringstream &operator<<(std::stringstream &stream, char c)
声明的情况下,stream << 'Z'
会以异常的方式失败(由于char
没有过载,因此可以将其提升为短且命中的basic_ostream
,以及提升为time_t
且命中MyStream
(。我真的不想使用basic_ostream::put
(,因为多个写入的链接会看起来很难看(当然,如果这是最后的手段…(。所以这给了我两个问题:
basic_ostream::operator<<
没有char
过载的基本原理是什么?这都是因为字符编码吗- 有什么好的解决方案吗(除了使用
put
或char
过载之外,我还缺少什么(
更新
因此,从std::stringstream
继承与使用using
似乎解决了这个问题,但这让我陷入了与";从不从stl类继承";教义
我想这个问题是因为using
实际上并没有引入一种新的类型,因此产生了歧义:
类型别名声明引入了一个名称,该名称可以用作type-id表示的类型的同义词。它不会引入新类型,也不会更改现有类型名称的含义。
您可以通过使用std::ostream
而不是std::stringstream
实现过载来解决问题
std::ostream& operator<<(std::ostream &stream, std::time_t )
{
return stream;
}
std::ostream& operator<<(std::ostream &stream, const MyTime &)
{
return stream;
}
演示。