我将尝试模仿Visual Studio中Intellisense的功能,当您在调试时悬停在位枚举变量(或类似名称)上时,将枚举转换为字符串。例如:
如果你将鼠标悬停在
#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中是否有类似的功能或可用于提供此功能?
如果没有,实现这样的功能最有效的方法是什么?(或者我的方法足够了吗)
singleFlagToString()
是什么?你是不是想调用ColorToString()
呢?乍一看,其他的都没问题,但我会使用位移操作而不是index % 2
。 - πάντα ῥεῖstd::function
,它接受枚举并将其转换为const char*
。目的是尽可能地通用,因此如果您注意到,我使用第二个参数ColorToString
调用了BitwiseEnumToString
。 - ZivSindex % 2
?我可能可以使用index & 0x1 == 0
,但这不是位移操作,对吧? - ZivS