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;
return str << std::setprecision(3) << std::fixed;? I mean functionally rather than stylistically.str is not a stream here, so this would not work I think.std::ostream& instead, but that wouldn't be as generic?std::ios_base in this case is that it is more generic (you could make the yours a bit more generic but it would require a template). I also prefer std::ios_base because it is the one used by std::fixed and alike manipulator.
#define.