c++ stream iword、pword和register_callback函数

4 篇文章 0 订阅
3 篇文章 0 订阅

pword,stream 的 register_callback函数

#include <iostream>
#include <sstream>
using namespace std;


const int name_index = std::ios::xalloc();

void SetStreamName (std::ios& stream, const char* name) {
   stream.pword(name_index) = const_cast<char*>(name);
}

std::ostream& StreamName (std::ostream& os) {
   const char* name = static_cast<const char*>(os.pword(name_index));
   if (name) os << name;
   else os << "(unknown)";
   return os;
}

void cofmtflags(ios_base::event e,std::ios_base& strm,int arg){
    if(e==ios_base::copyfmt_event){
        cout<<"copy fmt event"<<endl;
        strm.pword(arg)=new char[]{"World"};
    }else if(e==ios_base::erase_event){
        cout<<"erase event"<<endl;
    }else if(e==ios_base::imbue_event){
        cout<<"imbue event"<<endl;
    }
}

int main(){
    ostringstream ostr("Hello");
    SetStreamName(ostr, "String");
    ostr.register_callback(cofmtflags,name_index);
    cout.copyfmt(ostr);
    cout<<StreamName<<"123"<<endl;
}

iword使用

#include <iostream>

using namespace std;
static const int iword_index=ios_base::xalloc();

std::ostream& fraction_spaces(std::ostream& strm){
    strm.iword(iword_index)=true;
    return strm;
}
std::ostream& no_fraction_spaces(std::ostream& strm){
    strm.iword(iword_index)=false;
    return strm;
}

class Fraction{
public:
    Fraction(int num,int den):num(num),den(den){}
    int numerator() const{
        return num;
    }
    int denominator() const{
        return den;
    }

private:
    int num;
    int den;
};

ostream& operator<<(ostream& strm,const Fraction& f){

    if(strm.iword(iword_index)){
        strm<<f.numerator()<< " / "<<f.denominator();
    }else{
        strm<<f.numerator()<<"/"<<f.denominator();
    }
    return strm;
}

int main5(){
    Fraction df(11,22);

    cout<<df<<endl;

    cout<<fraction_spaces<<df<<endl;
    cout<<no_fraction_spaces<<df<<endl;

}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值