-1

I want to programmatically retrieve the identifier of a C++ class instance at runtime. I'm aware that C++ doesn't support reflection yet, but is there any alternative solution out there? For instance, given the following example:

class Foo {
  Foo() {
   auto name = reflect::getIdentifierName(this);
   std::cout << name << std::endl;
  }
};

void main() {
   Foo my_obj;
}

Executing this program should print out "my_obj". I'm looking for any utility library that I could use to implement this basic reflection function.

I'm particularly wondering if libclang can be used to extract such information - if so, any hint for how to build the reflect function to do this.

Blaise Tine
  • 61
  • 1
  • 5
  • That is not the class name, that is the identifier of the object. Did you consider giving the name as a string to constructor, storing it and returning it from a getter? – Yunnosch Dec 02 '17 at 09:17
  • 1
    An object doesn't have a name, a variable does. There isn't a 1:1 relationship between objects and variables, in general. – Oliver Charlesworth Dec 02 '17 at 21:12
  • I'm looking for a tool that can help programmatically retrieve the name of the class object instance (not the name of the class). Any parser tool for instance. – Blaise Tine Dec 03 '17 at 08:11

1 Answers1

1

Yes, but this is implementation defined. Proceed at your own risk.

Yunnosch's suggestion sounds much more reasonable without more context.

#include <iostream>
#include <typeinfo>

class Foo {
public:
  Foo() {
   const char * const name = typeid(this).name();
   std::cout << name << std::endl;
  }
};

int main()
{
   Foo my_obj;
}
tweej
  • 832
  • 4
  • 16
  • Thank you for this answer. this solution will output "Foo" which is not "my_obj", I'm looking for a way to print out the class instance variable, not the class name. – Blaise Tine Dec 02 '17 at 12:08
  • What is this "class instance variable" you speak of? I am not aware of any automatically provided variable, but you can make your own by using a static variable or by just using the this pointer to get the unique address of each object. – tweej Dec 02 '17 at 19:02