2012-07-19 56 views
1

我在我的C#項目中使用Enum.GetValuesEnum.GetName,想知道標準C++庫中是否有其他替代方法?將C#應用程序轉換爲C++枚舉

+3

題外話:這是一個可怕的問題標題。它表明你想要將一個完整的C#應用​​程序表達爲一個C++枚舉......這顯然是無稽之談。請選擇一個更精確和有意義的標題。 – stakx 2012-07-19 19:16:20

回答

1

有沒有簡單的方法來做到這一點。有關於這個問題的一些做題(不完全是這個問題,雖然):

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

How to easily map c++ enums to strings

+0

雖然問題稍有不同,但是「有沒有簡單的腳本來將C++枚舉轉換爲字符串?」的頂級解決方案?對這個問題也是一個很好的解決方案。您可以使用GCCXML在構建時從您的枚舉中生成XML描述,然後運行構建時腳本來讀取它,並生成C++代碼,用於初始化值數組和從值到名稱的std :: map。 – 2012-07-19 19:14:56

0

,如果你需要得到的所有功能,我會用一個STL ::地圖全部可能的名稱和相關的int值。

一般來說,在C++和使用枚舉中,您必須查看文檔以獲取所有可能的枚舉值或使用命名空間,或者讓IDE在編程時告訴您哪些可用。

有時,在編寫枚舉時,我會在所有命名值前加上一些信息,指明它們屬於哪個枚舉。

1

你可以推出自己的班級。

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

注:這可能是不完美的。它沒有經過測試,並且不可能在第一次嘗試時神奇地工作。