I would like a setw to take two parameters and return the largest. Is this possible? How do I go about doing this? Not looking for code just some direction would be fine as I couldn't find a clear answer on-the-line.
Asked
Active
Viewed 546 times
0
-
You cannot overload it directly since it resides in namespace std (and adding custom overloads there is forbidden generally). I think it's possible to use some name lookup tricks to overload it in another namespace; but I don't quite see the advantage over Remy Lebeau's solution. – dyp Sep 08 '14 at 20:22
1 Answers
3
I don't think you can overload it, but you can certainly define your own type with a different name and then define <<
and >>
operators for it. For example:
struct setw_largest
{
int _value;
setw_largest(int value1, int value2) : _value(std::max(value1, value2)) {}
};
template<class _Elem, class _Traits, class _Arg>
inline basic_istream<_Elem, _Traits>& operator>>(basic_istream<_Elem, _Traits>& _Istr, const setw_largest& _Manip)
{
_Istr.width(_Manip._value);
return _Istr;
}
template<class _Elem, class _Traits, class _Arg>
inline basic_ostream<_Elem, _Traits>& operator<<(basic_ostream<_Elem, _Traits>& _Ostr, const setw_largest& _Manip)
{
_Ostr.width(_Manip._value);
return _Ostr;
}
std::cin >> setw_largest(1, 2) >> ...;
std::cout << setw_largest(1, 2) << ...;

Remy Lebeau
- 555,201
- 31
- 458
- 770
-
The STL consists of mostly header files and inline implementations, so you can simply look at the `setw()` implementation to see what it actually does. – Remy Lebeau Sep 08 '14 at 20:17
-
Underscore + capital letter = reserved identifier, [global.names]. This is intended in an StdLib implementation, but your own extensions shouldn't use them. – dyp Sep 08 '14 at 20:19
-
I will tackle this and give you feedback later. Thanks for the help. – Alexander Sep 08 '14 at 20:20