Can I get an object\'s name in run time (like getting an object\'s type via RTTI)? I want the object to be able to print its name.
So, this is basically what I did. It's hacky, but it does the trick. I created a variadic macro that takes advantage of stringizing. Unfortunately, it becomes clumsy with the need for a _dummy parameter in order to provide the pseudo-default ctor, because you cannot omit the comma separating the named argument from the variable arguments (I even tried with gnu cpp, but was unsucessful--may I didn't try hard enough).
#include
#define MyNamedClass( objname, ... ) MyClass objname(__VA_ARGS__, #objname )
class MyClass
{
public:
MyClass( void* _dummy=nullptr, const std::string& _name="anonymous") : name( _name ) {}
MyClass( int i, const std::string& _name="anonymous" ) : name( _name ) {}
private:
std::string name;
};
int main()
{
MyClass mc0;
MyClass mc1(54321);
MyNamedClass( mc2, nullptr);
MyNamedClass( mc3, 12345 );
return 0;
}