这是一个写起来很有趣的解决方案,但我几乎不希望出现这种解决方案。它也可能具有一些娱乐和/或教育价值。基本思想是值 a 写为
std::cout << 10 << 15 << 11 << reset << '\n';
std::cout << 1 << 2 << 3 << reset << '\n';
为了实现这一点,需要一些机器,但它并没有那么糟糕,真的。代码很糟糕:
#include <locale>
#include <iostream>
#include <algorithm>
static int index(std::ios_base::xalloc());
static std::string const names[] = { "One", "Two", "Three", "Four", "Five" };
static std::string const score("Score_");
static std::string const other(" (Which would be ");
std::ostream& reset(std::ostream& out)
{
out.iword(index) = 0;
return out;
}
struct num_put
: std::num_put<char>
{
iter_type do_put(iter_type to, std::ios_base& fmt, char_type fill,
long v) const {
to = std::copy(score.begin(), score.end(), to);
if (fmt.iword(index) < 5) {
to = std::copy(names[fmt.iword(index)].begin(),
names[fmt.iword(index)].end(), to);
++fmt.iword(index);
}
else {
throw std::runtime_error("index out of range!");
}
to = std::copy(other.begin(), other.end(), to);
to = this->std::num_put<char>::do_put(to, fmt, fill, v);
*to++ = ')';
*to++ = ' ';
return to;
}
};
int main()
{
std::cout.imbue(std::locale(std::locale(), new num_put));
std::cout << 10 << 15 << 11 << reset << '\n';
std::cout << 1 << 2 << 3 << reset << '\n';
}