自定义输出流状态

一般,要想改变流对下一个对象的输出方式,需要使用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的代码

#ifndef MY_ios_state_HEADER
#define MY_ios_state_HEADER

#include 
   
   
    
    
#include 
    
    
     
     
#include 
     
     
      
      
#include 
      
      
       
       
#include 
       
       
         #include 
        
          #include 
         
           #include 
          
            #include 
           
             namespace ios_state { template 
            
              class format_t : public boost::intrusive_ref_counter 
              
              , boost::sp_adl_block::thread_unsafe_counter> { public: using intrusive_ptr = boost::intrusive_ptr 
               
                 ; template 
                
                  static intrusive_ptr instance(Args... args) noexcept(std::is_nothrow_constructible 
                 
                   ::value) { return new format_t{ std::forward 
                  
                    (args)... }; } private: Data data; template 
                   
                     format_t(Args... args) noexcept(std::is_nothrow_constructible 
                    
                      ::value) : data(std::forward 
                     
                       (args)...) {} enum tag_t { DATA = 0, CALL_BACK_TAG, TOTAL }; static int get_index(tag_t const tag) noexcept(noexcept(std::ios_base::xalloc())) { static const int index[TOTAL] = { std::ios_base::xalloc(),std::ios_base::xalloc() }; return index[tag]; } using event_t = std::ios_base::event; static void call_back(event_t type, std::ios_base& ios, int index) noexcept { auto const ptr = get_intrusive_ptr(ios).get(); if (ptr) { switch (type) { case std::ios_base::erase_event: intrusive_ptr_release(ptr); break; case std::ios_base::copyfmt_event: intrusive_ptr_add_ref(ptr); break; } } } static intrusive_ptr& get_intrusive_ptr(std::ios_base &ios) noexcept { return reinterpret_cast 
                      
                        (ios.pword(get_index(DATA))); } template 
                       
                         friend std::basic_ostream 
                        
                          & operator<<(std::basic_ostream 
                         
                           & ostr, intrusive_ptr format) noexcept { long& tag = ostr.iword(get_index(CALL_BACK_TAG)); if (!tag) {// 没有注册过回调函数 tag = true; ostr.register_callback(&call_back, get_index(DATA)); } get_intrusive_ptr(ostr).swap(format); return ostr; } template 
                          
                            friend Data_ const& get_data(std::ios_base &ios); }; template 
                           
                             inline Data_ const& get_data(std::ios_base &ios) { using format_t_ = format_t 
                            
                              ; auto ptr = reinterpret_cast 
                             
                               (ios.pword(format_t_::get_index(format_t_::tag_t::DATA))); if (ptr) return ptr->data; throw std::runtime_error{ "format_t data not set" }; } } #define _IOS_STATE_MANIPULATOR_NO_CLEAR(class_name, setter)\ template 
                              
                                \ auto setter(Args... args) noexcept(noexcept(class_name::instance(std::forward 
                               
                                 (args)...))) {\ return class_name::instance(std::forward 
                                
                                  (args)...);\ } #define _IOS_STATE_FORMAT_2(data, setter)\ _IOS_STATE_MANIPULATOR_NO_CLEAR(::ios_state::format_t 
                                 , setter) #define _IOS_STATE_MANIPULATOR_WITH_CLEAR(class_name, setter, clear)\ _IOS_STATE_MANIPULATOR_NO_CLEAR(class_name, setter)\ auto clear() noexcept {\ return class_name::intrusive_ptr{ nullptr };\ } #define _IOS_STATE_FORMAT_3(data, setter, clear)\ _IOS_STATE_MANIPULATOR_WITH_CLEAR(::ios_state::format_t, setter, clear) #define IOS_STATE_FORMAT(...)\ BOOST_PP_CAT(BOOST_PP_OVERLOAD(_IOS_STATE_FORMAT_, __VA_ARGS__)(__VA_ARGS__), BOOST_PP_EMPTY()) #endif  
                                 
                                
                               
                              
                             
                            
                           
                          
                         
                        
                       
                      
                     
                    
                   
                  
                 
                
              
             
            
           
          
         
       
      
      
     
     
    
    
   
   

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

cqdjyy01234

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值