3 回答

TA貢獻2051條經驗 獲得超10個贊
首先,您必須將一些狀態存儲到每個流中。您可以使用函數iword和傳遞給它的索引來實現,該函數由給出xalloc:
inline int geti() {
static int i = ios_base::xalloc();
return i;
}
ostream& add_one(ostream& os) { os.iword(geti()) = 1; return os; }
ostream& add_none(ostream& os) { os.iword(geti()) = 0; return os; }
有了適當的設置,您已經可以在所有流中檢索某些狀態?,F在,您只需要加入相應的輸出操作即可。數值輸出由構面完成,因為它可能取決于語言環境。所以你可以做
struct my_num_put : num_put<char> {
iter_type
do_put(iter_type s, ios_base& f, char_type fill, long v) const {
return num_put<char>::do_put(s, f, fill, v + f.iword(geti()));
}
iter_type
do_put(iter_type s, ios_base& f, char_type fill, unsigned long v) const {
return num_put<char>::do_put(s, f, fill, v + f.iword(geti()));
}
};
現在,您可以測試這些東西了。
int main() {
// outputs: 11121011
cout.imbue(locale(locale(),new my_num_put));
cout << add_one << 10 << 11
<< add_none << 10 << 11;
}
如果您只想增加下一個數字,只需0在每次調用后將單詞再次設置為do_put。

TA貢獻1796條經驗 獲得超4個贊
我完全同意Neil Butterworth的觀點,但是在特定情況下,您使用的是這種完全駭人聽聞的技巧。不要在任何生產代碼中執行此操作。它有很多錯誤。一方面,它僅適用于您的單行代碼,而不會更改基礎流的狀態。
class plusone_stream : public std::ostream
{
public:
std::ostream operator<<(int i)
{
_out << i+1;
return *this;
}
};
std::ostream& plusone(std::ostream& out)
{
return plusone_stream(out);
}
- 3 回答
- 0 關注
- 488 瀏覽
添加回答
舉報