C++ type_info成员函数是如何工作的?
我目前正在学习运行时类型ID和强制转换操作符。我有一些问题,你能帮我解决这些疑问吗 请参阅以下代码:C++ type_info成员函数是如何工作的?,c++,C++,我目前正在学习运行时类型ID和强制转换操作符。我有一些问题,你能帮我解决这些疑问吗 请参阅以下代码: #include <iostream> #include <typeinfo> using namespace std; class base { }; class derived { }; int main() { cout<<typeid(char).name()<<endl; cout
#include <iostream>
#include <typeinfo>
using namespace std;
class base
{
};
class derived
{
};
int main()
{
cout<<typeid(char).name()<<endl;
cout<<typeid(int).name()<<endl;
cout<<typeid(float).name()<<endl;
cout<<typeid(double).name()<<endl;
cout<<typeid(base).name()<<endl;
cout<<typeid(derived).name()<<endl;
}
问题:
typeid(base).name()给出“4base
”;这里的4
和typeid(派生).name()给出了“7derived
”;这里的7
是什么
typeid(char).name()和其他内置数据类型只给出第一个字母
type_info::before()
函数感谢您的时间和回答。
type_info::name
返回实现定义的类型名称。它不一定与代码中这些类型名称的实际拼写相对应
GCC和Clang返回,因为这就是这些类型名在内部的表示方式。您可以通过实现名称更改规则手动对其进行更改,也可以使用现有工具,如c++filt
或
type_info::before
没有直接的用处。它的价值本质上是任意的,但却是一致的。这使得它可用于将type_info
对象存储在已排序的容器中,例如std::set
,或将它们用作std::map
中的键std::type_info::before
可以在这里用作排序关系。或者,type_info
可能重载了操作符
before(*b); }; 使用类型\u name\u map=std::map< std::type_info const*, 字符常量*, decltype(无类型信息) >; 自动常量可读类型名称=类型名称映射( { {&typeid(int),“int”}, {&typeid(float),“float”}, {&typeid(std::string),“std::string”}, // ... }, 键入\u信息\u less ); 模板 自动类型_name(){ 返回可读的类型名称。查找(&typeid(T))->second; } int main(){
std::cout名称是实现定义的。如果需要,它们可以返回puppies。如果您想要可读的名称,对于gcc,请参阅。乍一看,4和7分别是“base”和“derived”的长度。如果您查看Andrei的链接,看起来这个长度前缀是gcc的混乱方案中字符串名称的分隔方式。@AndreiDamian虽然这是真的,但并不能真正解释原因,这是一个非常有效的问题。@KonradRudolph对此的回答是“因为他们可以”。我会理解前两个问题,但我不明白什么是type_info::before,我在google中搜索了type_info::before,但我无法得到他们说的内容,所以请您解释一下。谢谢您的回答。我不知道type_info::before如何返回0或1。在一些网站上,他们说函数在实现排序或排序后返回但是这是什么?@Srilakshmikanthanp它返回一个,而不是0或1。“排序顺序”是一种愚蠢的复杂方式,表示它的功能类似于bool
c i f d 4base 7derived Process returned 0 (0x0) execution time : 0.238 s Press any key to continue.
#include <iostream> #include <map> #include <string> #include <typeinfo> auto type_info_less = [](std::type_info const* a, std::type_info const* b) { return a->before(*b); }; using type_name_map = std::map< std::type_info const*, char const*, decltype(type_info_less) >; auto const readable_type_names = type_name_map( { {& typeid(int), "int"}, {& typeid(float), "float"}, {& typeid(std::string), "std::string"}, // ... }, type_info_less ); template <typename T> auto type_name() { return readable_type_names.find(& typeid(T))->second; } int main() { std::cout << type_name<std::string>() << "\n"; // Prints ”std::string”. }