Is there a way to create a shorthand alias for the following line in C++98?
std::precision(3) << std::fixed
And then use the alias as follows:
std::cout << alias << 3.1415926 << std::endl;
The standard way would probably be to create a custom manipulator:
std::ios_base& alias(std::ios_base& str) {
str.precision(3);
return std::fixed(str);
}
Then:
std::cout << alias << 3.16464;
See overload (9) of operator<<
:
basic_ostream& operator<<(std::ios_base& (*func)(std::ios_base&))
If you want to specify arguments, you need an intermediate structure:
struct alias_t {
int n;
};
alias_t setalias(int n) { return {n}; }
template <class CharT, class Traits>
std::basic_ostream<CharT, Traits>&
operator<<(std::basic_ostream<CharT, Traits>& out, const alias_t& alias) {
return out << std::fixed << std::setprecision(alias.n);
}
// Or if you do not care about genericity:
std::ostream& operator<<(std::ostream& out, const alias_t& alias) {
return out << std::fixed << std::setprecision(alias.n);
}
Then:
std::cout << setalias(6) << 3.16464;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With