【问题标题】:Converting C# application to C++ enum将 C# 应用程序转换为 C++ 枚举
【发布时间】:2012-07-19 19:05:08
【问题描述】:

我在我的 C# 项目中使用了 Enum.GetValuesEnum.GetName,想知道标准 C++ 库中是否有某种替代方法?

【问题讨论】:

  • 离题:这是一个糟糕的问题标题。它表明您想将完整的 C# 应用程序表示为 C++ 枚举......这显然是无稽之谈。请选择一个更准确、更有意义的标题。

标签: c# c++ enums


【解决方案1】:

没有简单的方法可以做到这一点。关于这个主题有一些 SO 问题(虽然不完全是这个问题):

Is there a simple way to convert C++ enum to string?

How to easily map c++ enums to strings

【讨论】:

  • 虽然问题略有不同,但在“是否有一个简单的脚本可以将C++枚举转换为字符串?”中的顶级解决方案也是这个问题的一个很好的解决方案。您使用 GCCXML 在构建时从枚举生成 XML 描述,然后运行构建时脚本读取它并生成 C++ 代码,该代码初始化值数组和从值到名称的 std::map。
【解决方案2】:

你可以自己动手上课。

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);
}

注意:这可能并不完美。它未经测试,不太可能在第一次尝试时神奇地发挥作用。

【讨论】:

    【解决方案3】:

    如果您需要获取所有可能名称和相关 int 值的所有功能,我会使用 stl::map。

    一般来说,在 c++ 和使用枚举中,您必须查看文档以获取所有可能的枚举值或使用命名空间,或者让 IDE 在您编程时告诉您哪些可用。

    有时,在编写枚举时,我会在所有命名值前面加上一些信息,表明它们属于哪个枚举。

    【讨论】:

      猜你喜欢
      • 2020-08-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-08-12
      • 1970-01-01
      • 2010-09-17
      相关资源
      最近更新 更多