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;
}