像这样:
class Blah { static std::string const className() { return "Blah"; }};
std::string const name = Blah::className();
assert(name == "Blah");
或者这样:
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");
票友:
#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();
...
或者这样:
class Blah : QObject { Q_OBJECT };
或者这样:...... 或者这样:...
另一种解决方案将被TYPEID()+还原函数。否则,你如何处理命名空间等? – 2010-12-16 23:00:39
typeid不保证是不可升级的。 – quetzalcoatl 2012-09-03 21:32:52
第一种情况是唯一严重的情况。它易读,易于维护和使用。第二个过度复杂化一个简单的问题。也许你宁愿使用REST api来调用web服务呢?第三个被认为是坏习惯。当涉及到良好的设计时,预处理器是最糟糕的,也是最不应该使用的。对于预处理器,我能想到的唯一合理用例是编译指示一次。 – nali 2017-12-05 22:25:55