Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

get static int variable class name with typeid(*this).name for its own definition - C++

When I need to get the class name inside of one of its methods I just call:

typeid(*this).name()

(then I split the result into tokens and get the class name)

Now I have to define a static member variable and need to get the class name for that. But I`m not in a method! So, I cannot use (*this).

Initially, I thought I could do something like:

#define INIT_STAT_VAR
   const char * cname = typeid(*this).name;
   int cname##::var = 1;

Any idea how I could get the class name for the static member variable definition? ( no, I cannot just write the name of the class directly for the definition ;] )

thanks!

like image 805
sciloop Avatar asked Jan 30 '26 22:01

sciloop


1 Answers

I don't think it is directly possible to do what you want - as a static method doesn't get an object pointer it can't call typeid on it. You could create a temporary object in the static method and use that on typeid, but that pretty much goes against having it as a static method.

Another solution (if you can guarantee that at least 1 instance of the class is defined) would be to create a static member variable which you initialise once in the Constructor, and then access from a static method. It's a little hacky, but works:

#include <typeinfo>
#include <string>

class Foo {
public:
  Foo() {
    if (name == NULL) {
      const std::type_info& id = typeid(*this);
      name = new std::string(id.name());
    }
    // Normal object creation.
  }

  static std::string getName() { return *name; }

private:
  static std::string* name;
};

std::string* Foo::name = NULL;
like image 65
DaveR Avatar answered Feb 01 '26 10:02

DaveR