Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get struct member with a string using Macros C++

Tags:

c++

macros

Consider the following example:

struct MyStruct {
    int a;
    int b;
};

I can use macros to set a member from an instance of the struct by doing this:

#define setVar(x,y) instance.x = y

then in any function I can say:

setVar(a, 4)

How can I send in a as a string to the macro? Is that also possible?

setVar("a", 4)

EDIT: There are a bunch of predefined structs with members that are all of type double. I only know what struct I am using by an XML config file that is passed in. After parsing, I have a bunch of strings that are a list of all the data members and values that need to be set. I need to use this list to set values for each of the members in the struct.

like image 746
ulu5 Avatar asked May 04 '12 15:05

ulu5


1 Answers

It is only possible if you define the struct itself using some macro, for example:

#define MY_STRUCT_STRUCTURE FIELD(a) FIELD(b) FIELD(d) FIELD(e) FIELD(f)

struct MyStruct {

# define FIELD(name) int name;
    MY_STRUCT_STRUCTURE
# undef FIELD

  bool setVar(char* fieldname, int val)
  {
#   define FIELD(name) if(strcmp(#name,fieldname)==0){name=val; return true;};
    MY_STRUCT_STRUCTURE
#   undef FIELD
    return false; // name not found
  }
};


int main()
{
  MyStruct s;
  s.setVar("a",1);
  s.setVar("b",2);
  s.setVar("f",100);
}
like image 155
user396672 Avatar answered Sep 20 '22 06:09

user396672