自定义输出流状态

来源:互联网 发布:tao淘宝网 编辑:程序博客网 时间:2024/06/05 15:57

一般,要想改变流对下一个对象的输出方式,需要使用manipulator,如:setw, setfill等。通过定义functor,用户可以很容易定义自己的manipulator。但是如果想要添加流状态(类似于对流中存储的整数的输出进制),却不那么容易,需要使用xalloc, pword, iword等。


假设现在需要输出一些变量。因为存储字符串代价比较高,通常会用整数关键字来代表它们。这样在输出的时候需要进行转化,将整数对应的字符串输出。如果对变量的输出出现在多个地方,那么在输出的时候不一定可以访问存储变量名的表。显然,可以通过将表存为全局变量来解决这一问题。


下面通过名为ios_state.h的头文件(见最后)提供问题的另一种解决方案


#include <ios_state.h>#include <vector>#include <string>#include <iostream>namespace custom {using table_t = std::vector<std::string>;IOS_STATE_FORMAT(table_t, set_table, clear_table)struct var_wrapper {int var;};std::ostream& operator<<(std::ostream& ostr, var_wrapper const var) {return ostr << ios_state::get_data<table_t>(ostr)[var.var];}}void print() {using namespace custom;std::cout << var_wrapper{ 0 } << " "<< var_wrapper{ 1 } << " "<< var_wrapper{ 2 } << "\n";}int main() {custom::table_t table{ "a", "b", "c" };try {std::cout << custom::set_table(table);print();std::cout << custom::clear_table();print();}catch (std::runtime_error const &err) {std::cerr << err.what() << "\n";}return 0;}


下面是ios_state.h的代码


0 0
原创粉丝点击