Nor*_*löw 7 c++ formatting interpretation ostream
我想控制我ostream输出的chars和unsigned char's via是否<<将它们写成字符或整数.我在标准库中找不到这样的选项.现在我已经恢复了在一组替代打印功能上使用多个重载
ostream& show(ostream& os, char s) { return os << static_cast<int>(s); }
ostream& show(ostream& os, unsigned char s) { return os << static_cast<int>(s); }
Run Code Online (Sandbox Code Playgroud)
有没有更好的办法?
我有一个基于how do I print an unsigned char as hex in c++ using ostream? 中使用的技术的建议。。
template <typename Char>
struct Formatter
{
Char c;
Formatter(Char _c) : c(_c) { }
bool PrintAsNumber() const
{
// implement your condition here
}
};
template <typename Char>
std::ostream& operator<<(std::ostream& o, const Formatter<Char>& _fmt)
{
if (_fmt.PrintAsNumber())
return (o << static_cast<int>(_fmt.c));
else
return (o << _fmt.c);
}
template <typename Char>
Formatter<Char> fmt(Char _c)
{
return Formatter<Char>(_c);
}
void Test()
{
char a = 66;
std::cout << fmt(a) << std::endl;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1121 次 |
| 最近记录: |