【发布时间】:2012-07-19 19:05:08
【问题描述】:
我在我的 C# 项目中使用了 Enum.GetValues 和 Enum.GetName,想知道标准 C++ 库中是否有某种替代方法?
【问题讨论】:
-
离题:这是一个糟糕的问题标题。它表明您想将完整的 C# 应用程序表示为 C++ 枚举......这显然是无稽之谈。请选择一个更准确、更有意义的标题。
我在我的 C# 项目中使用了 Enum.GetValues 和 Enum.GetName,想知道标准 C++ 库中是否有某种替代方法?
【问题讨论】:
没有简单的方法可以做到这一点。关于这个主题有一些 SO 问题(虽然不完全是这个问题):
【讨论】:
你可以自己动手上课。
Widget.h:
#include <map>
#include <string>
using namespace std;
class Widget
{
public:
static Widget VALUE1, VALUE2, VALUE3;
type GetValue();
string GetName();
bool Widget::operator==(const Widget& other) const;
private:
// specific traits should be declared here
int i;
Widget(string name, int value);
static map<Widget, string> names;
}
Widget.cpp:
Widget::VALUE1 = Widget("VALUE1", 1);
// others
Widget::Widget(string name, int value)
{
i = value;
Widget::names[name] = *this; // this should happen after all initialization is done
}
bool Widget::operator==(const Widget& other) const
{
return (this->i == other.i);
}
注意:这可能并不完美。它未经测试,不太可能在第一次尝试时神奇地发挥作用。
【讨论】:
如果您需要获取所有可能名称和相关 int 值的所有功能,我会使用 stl::map。
一般来说,在 c++ 和使用枚举中,您必须查看文档以获取所有可能的枚举值或使用命名空间,或者让 IDE 在您编程时告诉您哪些可用。
有时,在编写枚举时,我会在所有命名值前面加上一些信息,表明它们属于哪个枚举。
【讨论】: