I'm trying to do what Intellisense does in visual studio when you hover over a bitwise-enum (or however it's called) variable (while debugging), by taking an enum and converting it to string.
for example:
#include <iostream>
enum Color {
White = 0x0000,
Red = 0x0001,
Green = 0x0002,
Blue = 0x0004,
};
int main()
{
Color yellow = Color(Green | Blue);
std::cout << yellow << std::endl;
return 0;
}
If you hover over yellow
you'll see:
So I want to be able to call something like:
std::cout << BitwiseEnumToString(yellow) << std::endl;
and have the output print: Green | Blue
.
I wrote the following which tries to provide a generic way of for printing an enum:
#include <string>
#include <functional>
#include <sstream>
const char* ColorToString(Color color)
{
switch (color)
{
case White:
return "White";
case Red:
return "Red";
case Green:
return "Green";
case Blue:
return "Blue";
default:
return "Unknown Color";
}
}
template <typename T>
std::string BitwiseEnumToString(T flags, const std::function<const char*(T)>& singleFlagToString)
{
if (flags == 0)
{
return singleFlagToString(flags);
}
int index = flags;
int mask = 1;
bool isFirst = true;
std::ostringstream oss;
while (index)
{
if (index % 2 != 0)
{
if (!isFirst)
{
oss << " | ";
}
oss << singleFlagToString((T)(flags & mask));
isFirst = false;
}
index = index >> 1;
mask = mask << 1;
}
return oss.str();
}
So now I can call:
int main()
{
Color yellow = Color(Green | Blue);
std::cout << BitwiseEnumToString<Color>(yellow, ColorToString) << std::endl;
return 0;
}
I get the desired output.
I'm guessing that I couldn't find anything about it since I don't know how it's called, but anyways -
Is there something in std or boost that does that or can be used to provide this?
If not, what's the most efficient way to do such a thing? (or would mine suffic)