我知道它是不可能超载基本类型(流)运算符如下:
std::ostream & operator<<(std::ostream &stream, const double s) {
stream << std::scientific << std::showpos << std::setprecision(15) << std::to_string(s);
return stream;
}
Run Code Online (Sandbox Code Playgroud)
为基本类型定义全局格式选项的首选方法是什么?请注意,我想将格式应用于任何类型的输出流,而不仅仅是特定的流std::cout.欢迎使用C++ 11解决方案.任何提示?
您可以定义自己的操纵器来设置流格式化程序.您的操纵器必须符合<<操作员期望的格式:
basic_ostream& operator<<(
std::basic_ostream<CharT,Traits>& (*func)(std::basic_ostream<CharT,Traits>&) );
Run Code Online (Sandbox Code Playgroud)
例如:
template <class Char>
basic_ostream<Char>& format_double(basic_ostream<Char>& stream) {
return stream << std::scientific
<< std::showpos
<< std::setprecision(15);
}
Run Code Online (Sandbox Code Playgroud)
然后就做:
cout << format_double << 2.0;
Run Code Online (Sandbox Code Playgroud)
参考
笔记
操纵器有两种格式,一种ios_base是参数,另一种是a basic_ostream.您必须使用后者,因为未指定返回值是什么setprecision(int).例如,我的编译器(gcc-4.9)返回一个_Setprecision包含整数的<<结构,并为此结构定义一个特定的运算符basic_ostream.
重载流是一个坏主意,但您可以包装它们。如果您想要进行特殊但常见的预处理/后处理,请定义一个自定义(模板化)类,该类将流作为成员(可能在构造函数中受到影响),并在预处理输入和/或执行一些操作后将实际 io 委托给该流后处理后。
class Printer {
ostream &ost;
Printer(ostream& st): ost(st) {
// other initializations ...
}
Printer& operator << (double d) {
ost << std::scientific << std::showpos << std::setprecision(15) << std::to_string(s);
return *this;
}
// others: ostream conversion, other processing...
}
Run Code Online (Sandbox Code Playgroud)