среда, 22 апреля 2009 г.

Stream Manipulators and Iterators in C++

По следам статьи:
Stream Manipulators and Iterators in C++ на www.informit.com

#1 Standard Inserter
#include <iostream>
#include <iomanip>

using namespace std;

void fb( ios_base& os, int l )
{
ostream *pos = dynamic_cast<ostream*>(&os);
if (pos)
{
for( int i=0; i < l; i++ )
(*pos) << ' ';
};
}

_Smanip<int>
__cdecl fillblank(int no)
{
return (_Smanip<int>(&fb, no));
}

int main( )
{
cout << "10 blanks follow" << fillblank( 10 ) << ".\n";
}


#2.0 Custom Inserter
template<class _Tm>
struct omanip
{
typedef std::ostream & (__cdecl *t_pf)(std::ostream&, const _Tm&);

omanip(t_pf _pf, _Tm _A) : _pf(_pf), _Manarg(_A) {}

friend std::ostream& operator<<(std::ostream& s, omanip & sm)
{ (*sm._pf)(s,sm._Manarg); return s; }

t_pf _pf;
_Tm _Manarg;
};

std::ostream& setspaces(std::ostream &Out, const int &NumSpaces)
{
int CurrentWidth;
CurrentWidth = Out.width();
Out << std::setw(NumSpaces) << " ";
Out << std::setw(CurrentWidth);
return(Out);
}

omanip<int> spaces(int NumSpaces)
{
return omanip<int> (&setspaces, NumSpaces);
}

int main( )
{
cout << "12:20" << spaces(11) << "13:35" << spaces(4) << endl;
}


#2.1 Custom Inserter
struct fillpair {
char ch;
int cch;
};

std::ostream& fp( std::ostream& os, const fillpair &fp )
{
for ( int c = 0; c < fp.cch; c++ ) {
os << fp.ch;
}
return os;
}

omanip<fillpair> fill( char ch, int cch )
{
fillpair pair;

pair.cch = cch;
pair.ch = ch;
return omanip<fillpair>( fp, pair );
}

int main( )
{
cout << "10 dots coming" << fill( '.', 10 ) << "done" << endl;
}


#3 Binary read/write
template < typename T >
struct _binary_data {
_binary_data(T& val) : pValue(&val) { }
T* pValue;
};

template < typename T >
_binary_data<T> binary(T &val) {
return _binary_data<T>(val);
}

template < typename T >
std::ostream& operator<<(std::ostream &os, const _binary_data<T> &bin) {
os.write(reinterpret_cast<const char*>(bin.pValue), sizeof(T));
return os;
}

template < typename T >
std::istream& operator>>(std::istream &is, _binary_data<T> &bin) {
is.read(reinterpret_cast<char*>(bin.pValue), sizeof(T));
return is;
}
int Write(std::ostream& out )
{
...
out << binary(m_A);
out << binary(m_B);
out << binary(m_C);
}

int Read(std::istream& in)
{
...
in >> binary(m_A);
in >> binary(m_B);
in >> binary(m_C);
}

Комментариев нет:

Отправить комментарий