To expand fjardon's answer , you can create a default format for any type you want to use with a template, for example
cout << formatted(2.0) << ' ' << formatted(1.4,6) << ' ' << formatted(2.3f)
uses different prefixes, etc. This can be implemented through
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}; }
You can use specialization and / or SFINAE to distinguish between different types (floating point, integral, complex ...).
source share