Search code examples
c++stringification

Convert member variable name to a string


Can I enumerate char* members of a class (or struct) in C++? If so can I print the variables names as strings? Using pre-processor?

I have a class with all const char* members. It would be good if there was an elegant way to enumerate each member variable and check name as a string against a string key I am given.

Here is the sort of code which could be used?

Can anyone think of a way to do this?

class configitems {
public:
   configitems() : host(0), colour(0) {}
   const char* host;
   const char* colour;
   //... etc
};

int main() {

   configitems cfg;
   //cfg.colour = "red";

   //receive an config item as a string.  I want to check that the item is a valid one (eg is a 
   //variable of class configitem) and then populate it.

   //eg get colour=red so want to do something like this:
   if(isConfigItem("colour")) {
      cfg.<colour> = "red";
   }
   return 0;
}

Solution

  • As others have said, the name of a variable doesn't actually exist in the generated code once the compiler has finished compiling the code. It may exist in debug symbols or some such, but that's a horrible mess to try to reach into to determine where your variable is located [it may well reside in different places depending on whether the compiler currently is using a register or memory location to store its value, etc, etc].

    It is certainly possible to have a macro that produces the matching strin to a name in a parameter.

    However, it's probably better to use a different mechanism for configuration type things - a couple of obvious options are:

    1. Using a std::map<std::string, std::string>
    2. Using an array or a vector of std::pair<std::string, std::string>

    You could also have a piece of fixed code that understands different configuration settings and their translation to variables. It's not at all a bad solution as long as there aren't a huge number of them.

    Or you could build an array like this:

    enum config_vals
    {
        host,
        color,
        ...
        max_config
    };
    
    struct translation
    {
       const char *name;
       config_vals val;
    };
    
    #define TRANS(x) { #x, x }
    
    translation trans[]] = {
        TRANS(host),
        TRANS(color),
    };
    
    class configitems
    {
      ...
      std::string value[max_configs];
      ...
    }
    
    ... 
    
    configitems c;
    ...
    if (c.value[host] == "localhost") ...