Example of Nonassociative Parameterized Manipulators

The following example demonstrates that parameterized manipulators defined with IOMANIP or IOAPP are not associative. The parameterized manipulator mysetw() is defined with IOMANIP. mysetw() can be applied once in any statement, but if it is applied more than once, it causes a compile-time error. To avoid such an error, put each application of mysetw into a separate statement.

// Nonassociative parameterized manipulators
#include <iomanip.h>
iostream&  f(iostream & io, int i) {
     io.width(i);
     return io;
}
IOMANIP (int) mysetw(int i) {
   return IOMANIP(int) (f,i);
}
iostream_withassign ioswa;
void main() {
   ioswa = cout;
   int i1 = 8, i2 = 14;
   //
   // The following statement does not cause a compile-time
   // error.
   //
   ioswa << mysetw(3) << i1 << endl;
   //
   // The following statement causes a compile-time error
   // because the manipulator mysetw is applied twice.
   //
   ioswa << mysetw(3) << i1 << mysetw(5) << i2 << endl; 
   //
   // The following statements are equivalent to the previous
   // statement, but they do not cause a compile-time error.
   //
   ioswa << mysetw(3) << i1;
   ioswa << mysetw(5) << i2 << endl;
}