A Simple Example Using Streams
Here’s a simple example that exercises
RWbostream and
RWbistream through their respective abstract base classes,
RWvostream and
RWvistream:
#include <rw/bstream.h>
#include <rw/math/mathvec.h>
#include <fstream.h>
template<class T>
void save(RWMathVec<T>& a, RWvostream& v)
{
a.saveOn(v); // Save to virtual output stream
}
template<class T>
RWMathVec<T> recover(RWvistream& v)
{
RWMathVec<T> dupe;
dupe.restoreFrom(v);
return dupe;
}
int main()
{
RWMathVec<double> a(10, 0.0, 2.0); // 0, 2, 4, ..., 18
{
ofstream f("junk.dat", ios::out); // 1
RWbostream bostr(f); // 2
save(a, bostr);
} // 3
ifstream f("junk.dat", ios::in); // 4
RWbistream bistr(f); // 5
RWMathVec<double> b = recover(bistr); // 6
cout << a << endl; // Compare the vectors // 7
cout << b << endl;
}
Program output:
[
0 2 4 6 8
10 12 14 16 18
]
[
0 2 4 6 8
10 12 14 16 18
]
The job of function
save(
RWMathVec<T>& a,
RWvostream& v) is to save the vector
a to the virtual output stream
v. Function
recover(
RWvistream&) restores the results. These functions do not know the ultimate format with which the vector will be stored, although in this case it will be in binary format because the specializing classes are
RWbostream and
RWbistream. Here are some additional comments on particular lines: