There is the following code:

#define VAR_NAME(Var) (#Var) #include <cstdlib> #include <string> struct cfg_pair{ std::string marker, value; cfg_pair(const char * name): marker("\r\n"+std::string(name)+"=") {} bool Init(std::string &buffer){ if( marker.empty() ) return false; int beg = buffer.find(marker); if( beg < 0 ) return false; beg += marker.size(); int end = buffer.find("\r\n",beg); if( end < 0 ) end = buffer.size(); value = buffer.substr(beg,end-beg); return true; } }; int main(int argc, char** argv) { cfg_pair test(VAR_NAME(test)); printf("%s\n",test.marker.c_str()); return 0; } 

Is it possible to make the marker field initialized with the name of the created cfg_pair object without passing any arguments to the constructor? That is, just "from the inside" somehow take the name of the object (in this case, test )?

  • 3
    The concept of "object name" in the language is missing. A variable at compile time has an identifier, but it is no longer available at runtime. - VTT
  • one
    No, you can't do that. To transfer the name from the outside manually, as in your example is the only way. - AnT

1 answer 1

The type name of the object can be found through typeid : typeid (cfg_pair) .name (). The object name, as already noted in the comments, will disappear after compilation. There are no language tools to analyze the variable instance name (besides, there is no particular benefit from this).

You can do something like this with preprocessor macros, but why?

  • Understood thanks! - Iceman
  • Is it like this? The author of the question wanted the name of the object (in the example, test ). And typeid(cfg_pair).name() will cfg_pair encrypted class name cfg_pair . That is, it is not at all. - AnT
  • @AnT, I realized that what I need to do will not work, and typeid - yes, this is not what I checked - Iceman