Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

If I defined a class:

class Blah {};

How can I:

std::string const className = /* What do I need to do here? */;
assert( className == "Blah" );

I dont think typeid().name() is a good idea since it's compiler implementation specific. Is there anything provided by the C++ standard or Boost?

Note: If the class were inherited from Qt's QObject, I could easily use QMetaObject::className() to get the class name.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
388 views
Welcome To Ask or Share your Answers For Others

1 Answer

Like this:

class Blah { static std::string const className() { return "Blah"; }};

std::string const name = Blah::className();
assert(name == "Blah");

Or this:

class Blah {};

template < typename T > struct name;
template < > struct name<Blah> { static std::string value() { return "Blah"; }};

std::string const classname = name<Blah>::value();
assert(classname == "Blah");

Fancier:

#define DECLARE_NAMED_CLASS( Name ) 
struct Name;
template < > struct name<Name> { static std::string value() { return #Name; }};
struct Name

DECLARE_NAMED_CLASS(Blah) {};
std::string const className = name<Blah>::value();
...

Or this:

class Blah : QObject { Q_OBJECT };

Or this:... Or this: ...


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...