views:

295

answers:

3

Hi, first post here!

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!

+1  A: 

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;
Dave Rigby
thanks, that looks interesting, Dave. But unfortunately, if in the last lines code, there`s again the class name (Foo) then, I also could write directly the definition of my variable. Or don`t I understand correctly?
sciloop
@sciloop: Yeah, it's necessary to allocate storage for the static member, don't think there's a way around that.
Dave Rigby
yeah, after quite some hours of investigation I see I have to type the name in, every time I have another class...
sciloop
A: 

You can use typeid(ClassName).name() ... but then you could also do simply "ClassName".

cube
do you mean with (ClassName) and "ClassName" the specific class name?
sciloop
yes, the name of the class that has the method
cube
uh, but the point of my question was how to get that name by not typing it in ;]
sciloop
Yeah, I know :-)
cube
A: 

Use the __class__ macro, if your compiler supports it.

outis
unfortunately, there is no such thing, here (http://msdn.microsoft.com/en-us/library/b0084kay%28VS.80%29.aspx). I also couldn`t find that for the intel compiler. But maybe it will be part of c++x0 standard?
sciloop
I thought it was under consideration, but there's no sign of it in the current draft. D'oh.
outis