当您将鼠标悬停在按位枚举(或称为)变量(在调试时)上时,我正在尝试通过获取枚举并将其转换为字符串来执行 Intellisense 在 Visual Studio 中所做的事情。
例如:
#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;
}
如果您将鼠标悬停在上方,yellow
您会看到:
所以我希望能够调用类似的东西:
std::cout << BitwiseEnumToString(yellow) << std::endl;
并打印输出:Green | Blue
.
我写了以下内容,试图提供一种打印枚举的通用方法:
#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();
}
所以现在我可以打电话了:
int main()
{
Color yellow = Color(Green | Blue);
std::cout << BitwiseEnumToString<Color>(yellow, ColorToString) << std::endl;
return 0;
}
我得到了想要的输出。
我猜我找不到任何关于它的信息,因为我不知道它是怎么称呼的,但无论如何 -
std 或 boost 中有什么东西可以做到这一点或可以用来提供这个吗?
如果不是,那么做这种事情的最有效方法是什么?(或者我的就足够了)