C++ Bitflaged enum to string -
i'm trying intellisense in visual studio when hover on bitwise-enum (or it's called) variable (while debugging), taking enum , converting 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 hover on yellow
you'll see:
so want able call like:
std::cout << bitwiseenumtostring(yellow) << std::endl;
and have output print: green | blue
.
i wrote following tries provide generic way of printing 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 can call:
int main() { color yellow = color(green | blue); std::cout << bitwiseenumtostring<color>(yellow, colortostring) << std::endl; return 0; }
i desired output.
i'm guessing couldn't find since don't know how it's called, anyways -
is there in std or boost or can used provide this?
if not, what's efficient way such thing? (or mine suffic)
you're going have maintain list of string representations of enum, in vector, hard-coded, etc. 1 possible implementation.
enum color : char { white = 0x00, red = 0x01, green = 0x02, blue = 0x04, //any others } std::string enumtostr(color color) { std::string response; if(color & color::white) response += "white | "; if(color & color::red) response += "red | "; if(color & color::green) response += "green | "; if(color & color::blue) response += "blue | "; //do many colors wish if(response.empty()) response = "unknown color"; else response.erase(response.end() - 3, response.end()); return response; }
then make enumtostr function each enum want to, following same form
Comments
Post a Comment