像這樣:
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