要在fjardon's answer擴大,您可以創建任何類型的默認格式,您希望使用的模板,這樣
cout << formatted(2.0) << ' ' << formatted(1.4,6) << ' ' << formatted(2.3f)
使用不同的精度等。這可以通過
namespace io_formatting {
template<typename Tp>
struct manipulator
{
Tp val;
int prec;
manipulator(Tp x, int p=std::numeric_limits<Tp>::digits10)
: val(x), prec(p) {}
};
template<typename X>
inline std::ostream& operator<<(std::ostream&o, manipulator<X> const&m)
{
return o << std::scientific
<< std::showpos
<< std::setprecision(m.prec)
<< m.val;
}
}
template<typename Tp>
io_formatting::manipulator<Tp> formatted(Tp x) { return {x}; }
template<typename Tp>
io_formatting::manipulator<Tp> formatted(Tp x, int p) { return {x,p}; }
實施
您可以使用專業化和/或SFINAE來區分不同類型(浮點,積分,複雜...)。
您可以定義一個應用所需選項的操縱器。顯式是好的,隱含的是不好的。大致。 –
即使可能,您也不應該(想要)那樣做。這會讓你的代碼更難理解和維護。 – Walter
@ Cheersandhth.-Alf你能更明確嗎? – JorenHeit