I have a strongly typed enum and std::vector
of this type.
enum class Colors { red, green, blue };
std::vector v = { Colors::blue, Colors::red };
I trying to output v
to standard output via std::copy
.
std::copy(v.begin(), v.end(), std::ostream_iterator<Colors>(std::cout, " ");
Compilation failed because compiler do not know how to print Colors
. I can define operator <<
for colors, but it looks too excessive for me. Then try print int
values of v
elements.
std::copy(v.begin(), v.end()
, std::ostream_iterator<std::underlying_type<Colors>::type>>(std::cout, " ");
Compilation failed because it is prohibited to print Colors
to std::ostream_iterator<int>
. Ok. Then std::transform
can help.
std::transform(v.begin(), v.end()
, std::ostream_iterator<std::underlying_type<Colors>::type>(std::cout, " ")
, [&](Colors &c) -> std::underlying_type<Colors>::type
{
return std::underlying_type<Colors>::type(c);
}
);
However, this lambda looks ugly. Is there neater way to copy
or transform
vector of Colors
? Maybe boost has some way?
Of course, a loop can print, but I'd prefer to avoid explicit loop.
for(auto c : v)
{
std::cout << std::underlying_type<Colors>::type(c) << std::endl;
}
I have a lot of different enum class
es in my project. All of them I need to print out. I don't like idea to create operator <<
for each one individually. However, if I try to make templated operator <<
then I've got a global redefinition of this operator. And this is not what I actually want.
template <typename T>
std::ostream &operator << (std::ostream &_os, const T &_t) {
_os << typename std::underlying_type<T>::type(_t);
return _os;
}
operator<<
or using a range-based for loop? – Yuushi Mar 11 '14 at 13:08operator<<
because I do not want to multiply entities, if it possible. If it's not possible, then I will use the operator. I avoid loop because I like more "functional" style. – Loom Mar 11 '14 at 13:29