2011-03-11 39 views
2

我有一個結構(可以是類),它在「H」文件中定義:運行時類型和屬性識別在C++中

struct my_struct { 
    char * a; 
    char * b; 
    char * other_char; 
    char * hello; 
    // other 100 chars 
    // new chars can be added in future 
}; 

我用這個結構在我的項目。所以,我得到這個結構和通話功能的每一個屬性和值:

void foo(char* attribute_name, char* attribute_value) {...} 

有什麼辦法來動態獲取結構的屬性名稱和值?

我需要它,因爲結構不斷提高,我需要添加代碼,並重新編譯該項目。

我需要的是這樣的:

void foo(my_struct s) { 

    int attributes = s.getAttrSize(); 

    for (int i=0; i<attributes; ++i){ 
     char* attribute_name = s.getAttrName[i]; 
     char* attribute_value = s.getAttriValue[i]; 
    } 
} 

的感謝!

回答

5

號C++沒有反射,而這種要求表明可能差的設計。

變量名,給出了方便的編程階段,而不應被視爲對存在在運行時數據標識符。

但是,您可以創建std::map真實與字符串>對象的映射。從上面的鏈接

2

使用multimap而不是你的結構...
例如:

int main() 
{ 
    multimap<const char*, int, ltstr> m; 

    m.insert(pair<const char* const, int>("a", 1)); 
    m.insert(pair<const char* const, int>("c", 2)); 
    m.insert(pair<const char* const, int>("b", 3)); 
    m.insert(pair<const char* const, int>("b", 4)); 
    m.insert(pair<const char* const, int>("a", 5)); 
    m.insert(pair<const char* const, int>("b", 6)); 

    cout << "Number of elements with key a: " << m.count("a") << endl; 
    cout << "Number of elements with key b: " << m.count("b") << endl; 
    cout << "Number of elements with key c: " << m.count("c") << endl; 

    cout << "Elements in m: " << endl; 
    for (multimap<const char*, int, ltstr>::iterator it = m.begin(); 
     it != m.end(); 
     ++it) 
    cout << " [" << (*it).first << ", " << (*it).second << "]" << endl; 
} 
+0

爲什麼使用multimap而不是map? – Shuo 2011-03-11 14:11:18

0

您可以使用RTTI獲取有關實例類型的信息,但你不能得到類型成員的名字,如規定@Tomalak。我也同意他的看法,認爲這種需要可能表明了一種錯誤的做法。

無論如何,你可能想了解cppreflectionRTTI_Part1

0

具有單一結構超過100場不看對我非常好。不知道你的結構細節,但聽起來不像一個好的設計。但是,如果這是必須的,那麼您可以考慮使用字典(讀取地圖)來保存名稱(鍵)和值的集合。您可以根據需要爲字典添加儘可能多的名稱/值對,並且您的結構不再改變。