D
Dave
Hello all,
It is my understanding that there is not a portable way to write a
user-defined manipulator that takes arguments. Please consider below which,
for purposes of illustration, implements a manipulator similar to setw().
Presumably, I have broken a rule here and this program is non-conforming.
However, I cannot see what rule that would be. May I request those who are
so inclined to try and poke holes in it?
Thank!
Dave
#include <iostream>
#include <ostream>
#include <string>
using namespace std;
template<typename T, typename C>
class ManipInfra
{
public:
ManipInfra(
basic_ostream<C> &(*pFun)(basic_ostream<C> &, T),
T val
): manipFun_(pFun), val_(val)
{
}
void operator()(basic_ostream<C> &os) const
{
manipFun_(os, val_);
}
private:
T val_;
basic_ostream<C> &(*manipFun_)(basic_ostream<C> &, T);
};
template<typename T, typename C>
basic_ostream<C> &operator<<(
basic_ostream<C> &os,
const ManipInfra<T, C> &manip
)
{
manip(os);
return os;
}
ostream &setTheWidth(ostream &os, int n)
{
os.width(n);
return os;
}
ManipInfra<int, char> setWidth(int n)
{
return ManipInfra<int, char>(setTheWidth, n);
}
int main()
{
cout << setWidth(10) << right << "foo" << endl;
}
It is my understanding that there is not a portable way to write a
user-defined manipulator that takes arguments. Please consider below which,
for purposes of illustration, implements a manipulator similar to setw().
Presumably, I have broken a rule here and this program is non-conforming.
However, I cannot see what rule that would be. May I request those who are
so inclined to try and poke holes in it?
Thank!
Dave
#include <iostream>
#include <ostream>
#include <string>
using namespace std;
template<typename T, typename C>
class ManipInfra
{
public:
ManipInfra(
basic_ostream<C> &(*pFun)(basic_ostream<C> &, T),
T val
): manipFun_(pFun), val_(val)
{
}
void operator()(basic_ostream<C> &os) const
{
manipFun_(os, val_);
}
private:
T val_;
basic_ostream<C> &(*manipFun_)(basic_ostream<C> &, T);
};
template<typename T, typename C>
basic_ostream<C> &operator<<(
basic_ostream<C> &os,
const ManipInfra<T, C> &manip
)
{
manip(os);
return os;
}
ostream &setTheWidth(ostream &os, int n)
{
os.width(n);
return os;
}
ManipInfra<int, char> setWidth(int n)
{
return ManipInfra<int, char>(setTheWidth, n);
}
int main()
{
cout << setWidth(10) << right << "foo" << endl;
}