C++中是否有一个__CLASS__宏,它给出的类名类似于__FUNCTION__宏,它给出的函数名
发布于 2009-11-03 19:44:30
最接近的方法是调用typeid(your_class).name() --但这会产生编译器特定的乱码。
要在类中使用它,只需使用typeid(*this).name()
发布于 2013-04-03 06:24:02
使用typeid(*this).name()的问题是在静态方法调用中没有this指针。宏__PRETTY_FUNCTION__在静态函数和方法调用中报告类名。但是,这只适用于gcc。
下面是一个通过宏样式接口提取信息的示例。
inline std::string methodName(const std::string& prettyFunction)
{
    size_t colons = prettyFunction.find("::");
    size_t begin = prettyFunction.substr(0,colons).rfind(" ") + 1;
    size_t end = prettyFunction.rfind("(") - begin;
    return prettyFunction.substr(begin,end) + "()";
}
#define __METHOD_NAME__ methodName(__PRETTY_FUNCTION__)宏__METHOD_NAME__将返回<class>::<method>()形式的字符串,从__PRETTY_FUNCTION__提供的内容中裁剪返回类型、修饰符和参数。
对于仅提取类名的内容,必须注意捕获没有类的情况:
inline std::string className(const std::string& prettyFunction)
{
    size_t colons = prettyFunction.find("::");
    if (colons == std::string::npos)
        return "::";
    size_t begin = prettyFunction.substr(0,colons).rfind(" ") + 1;
    size_t end = colons - begin;
    return prettyFunction.substr(begin,end);
}
#define __CLASS_NAME__ className(__PRETTY_FUNCTION__)发布于 2015-08-27 21:27:26
我想推荐boost::typeindex,这是我从Scott Meyer的“有效的现代C++”中学到的。下面是一个基本的例子:
示例
#include <boost/type_index.hpp>
class foo_bar
{
    int whatever;
};
namespace bti =  boost::typeindex;
template <typename T>
void from_type(T t)
{
    std::cout << "\tT = " << bti::type_id_with_cvr<T>().pretty_name() << "\n";
}
int main()
{
    std::cout << "If you want to print a template type, that's easy.\n";
    from_type(1.0);
    std::cout << "To get it from an object instance, just use decltype:\n";
    foo_bar fb;
    std::cout << "\tfb's type is : "
              << bti::type_id_with_cvr<decltype(fb)>().pretty_name() << "\n";
}使用"g++ --std=c++14“进行编译会产生以下结果
输出
如果你想打印一个模板类型,这很容易。
T=双精度
要从对象实例中获取它,只需使用decltype:
fb类型为: foo_bar
https://stackoverflow.com/questions/1666802
复制相似问题