Custom output stream Status

Source: Internet
Author: User

In general, to change the flow of the next object output mode, you need to use manipulator, such as: SETW, Setfill and so on. By defining functor, users can easily define their own manipulator. However, if you want to add a stream state (similar to the output of an integer stored in convection), it is not so easy to use Xalloc, Pword, Iword, and so on.


Suppose you need to output some variables now. Because the storage strings are expensive, they are usually represented by integer keywords. This will require conversion at the time of output, and output the string corresponding to the integer. If the output of the variable appears in multiple places, the table that stores the variable name may not be accessible at the time of the output. Obviously, you can solve this problem by saving the table as a global variable.


The following is another solution that provides the problem through a header file named Ios_state.h (see Final)


#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);p rint (); Std::cout < ;< custom::clear_table ();p rint ();} catch (Std::runtime_error const &err) {Std::cerr << err.what () << "\ n";} return 0;}


Here is the code for ios_state.h


Custom output stream Status

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.