如何为多个流操作创建别名?
How to create an alias for multiple stream operations?
有没有办法在 C++98 中为以下行创建 shorthand 别名?
std::precision(3) << std::fixed
然后使用别名如下:
std::cout << alias << 3.1415926 << std::endl;
标准方法可能是创建自定义操纵器:
std::ios_base& alias(std::ios_base& str) {
str.precision(3);
return std::fixed(str);
}
然后:
std::cout << alias << 3.16464;
参见 operator<<
的重载 (9):
basic_ostream& operator<<(std::ios_base& (*func)(std::ios_base&))
如果你想指定参数,你需要一个中间结构:
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);
}
然后:
std::cout << setalias(6) << 3.16464;
有没有办法在 C++98 中为以下行创建 shorthand 别名?
std::precision(3) << std::fixed
然后使用别名如下:
std::cout << alias << 3.1415926 << std::endl;
标准方法可能是创建自定义操纵器:
std::ios_base& alias(std::ios_base& str) {
str.precision(3);
return std::fixed(str);
}
然后:
std::cout << alias << 3.16464;
参见 operator<<
的重载 (9):
basic_ostream& operator<<(std::ios_base& (*func)(std::ios_base&))
如果你想指定参数,你需要一个中间结构:
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);
}
然后:
std::cout << setalias(6) << 3.16464;