开发者

runtime type and attributes identification in c++

开发者_JS百科I have a struct (could be a class) which defined in 'h' file:

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

I use this struct in my project. So I'm getting every attribute and value of this struct and call function:

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

Is there any way to dynamically get attributes names and values of the struct?

I need it because struct constantly raising, and I need to add code and recompile the project.

I need something like this:

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

thanks!


No. C++ does not have reflection, and this requirement indicates a possible poor design.

Variable names are given for convenience at the programming stage, and should not be taken as identifiers for data that exists at run-time.

However, you can create a real string->object mapping with std::map.


Use multimap instead your structure...
example from above link:

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


You can use RTTI to get information about instantiated types, but you can't get type member names, as stated by @Tomalak. I also agree with him that this need may indicate a mistaken approach.

Anyway, you may like to read cppreflection or RTTI_Part1.


Having more than 100 fields in a single structure doesn't look very good to me. Don't know the details of your structure, but doesn't sound like a good design. However, if this is a must, then you can think of using a dictionary (read map) to keep a collection of names (the keys) and values. You can add as many name-value pairs to the dictionary as you want and your structure will no longer change.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜