如何获取类名? [英] How to get class name?

查看:146
本文介绍了如何获取类名?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我定义了一个类:

class Blah {};

我如何:

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



我不认为typeid()。name()是一个好主意,因为它编译器实现。有没有什么提供的C ++标准或Boost?

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?

注意:如果类继承自Qt的QObject,我可以很容易地使用 QMetaObject ::

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

推荐答案

像这样:

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 };

或者:...
或者:...

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

这篇关于如何获取类名?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆