c++有许多输出操纵符,例如ostream& flush(ostream&o)
,
它却可以使用cout<<flush,
这是如何做到的呢?
#include <iostream>
using namespace std;
char* to_hex(unsigned long x){
static char ret[20] = "0x0\0";
static char table[17]="0123456789ABCDE";
int i = 2;
if (x == 0){ return "0x0\0"; }
while(x!=0){
ret[i++] = table[x%16];
x /= 16;
}
ret[i--] = '\0';
int j = 2;
while(j<i){
ret[i] ^= ret[j];
ret[j] ^= ret[i];
ret[i] ^= ret[j];
++j;--i;
}
return ret;
}
class To_Hex{
public:
To_Hex(char* (* tohex)(unsigned long),unsigned long x) :m_tohex(tohex),m_x(x){}
void operator()(ostream& o)const{
o << (*m_tohex)(m_x);
}
private:
char* (* m_tohex)(unsigned long);
unsigned long m_x;
};
ostream& operator<<(ostream& o, const To_Hex& to){
to(o);
return o;
}
To_Hex hexconv(unsigned long x){
return To_Hex(to_hex,x);
}
int main(){
cout << to_hex(0) << ends << to_hex(16) << ends << to_hex(10) << endl;
//hexconv()-> const To_Hex-> operator<<()-> operator()-> to_hex()
cout << hexconv(0) << ends << hexconv(16) << ends << hexconv(10) << endl;
cout << hexconv(0) << ends << hexconv(16) << ends << hexconv(10) << endl;
cout << hexconv(0) << ends << hexconv(16) << ends << hexconv(10) << endl;
cout << hexconv(0) << ends << hexconv(16) << ends << hexconv(10) << endl;
return 0;
}