以编程方式检索 C++ 类名

Retrieving a c++ class name programmatically(以编程方式检索 C++ 类名)

本文介绍了以编程方式检索 C++ 类名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道是否可以在 C++ 中以字符串形式检索类的名称,而无需将其硬编码到变量或 getter 中.我知道在运行时实际上并没有使用这些信息,因此它不可用,但是是否可以创建任何宏来创建此功能?

I was wondering if it is possible in C++ to retrieve the name of a class in string form without having to hardcode it into a variable or a getter. I'm aware that none of that information is actually used at runtime, therefor it is unavailable, but are there any macros that can be made to create this functionality?

请注意,我实际上是在尝试检索派生类的名称,并且我使用的是 Visual C++ 2008 Express Edition.

May be helpful to note that I'm actually trying to retrieve the name of a derived class, and I'm using Visual C++ 2008 Express Edition.

推荐答案

可以使用typeid:

#include <typeinfo>

std::cout << typeid(obj).name() << "
";

但是,类型名称不是标准化的,并且在不同的编译器(甚至同一编译器的不同版本)之间可能会有所不同,并且通常不可读,因为它是 mangled.

However, the type name isn't standardided and may differ between different compilers (or even different versions of the same compiler), and it is generally not human readable because it is mangled.

在 GCC 和 clang(使用 libstdc++ 和 libc++)上,您可以使用 __cxa_demangle 函数(在 MSVC 上似乎没有必要拆解):

On GCC and clang (with libstdc++ and libc++), you can demangle names using the __cxa_demangle function (on MSVC demangling does not seem necessary):

#include <cxxabi.h>
#include <cstdlib>
#include <memory>
#include <string>

std::string demangle(char const* mangled) {
    auto ptr = std::unique_ptr<char, decltype(& std::free)>{
        abi::__cxa_demangle(mangled, nullptr, nullptr, nullptr),
        std::free
    };
    return {ptr.get()};
}

这将仍然不一定是可读的名称——例如,std::string 是实际类型的类型名称,它的完整类型名称在当前的 libstdc++ 是 std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char>>;相比之下,在当前的 libc++ 中,它是 std::__1::basic_string, std::__1::allocator;>.不幸的是,美化"类型别名并非易事.

This will still not necessarily be a readable name — for instance, std::string is a type name for the actual type, and its complete type name in the current libstdc++ is std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >; by contrast, in the current libc++ it’s std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >. "Prettifying" type aliases is unfortunately not trivial.

这篇关于以编程方式检索 C++ 类名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:以编程方式检索 C++ 类名

基础教程推荐