c++ - type_info 成员函数是如何工作的?
问题描述
我目前正在学习 Run-Time Type ID 和 Casting Operator。我有一些问题,你能帮我解决这个疑问吗?
请参阅以下代码:
#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;
}
输出:
c
i
f
d
4base
7derived
Process returned 0 (0x0) execution time : 0.238 s
Press any key to continue.
问题:
typeid(base).name()
给出“4base
”;这里有什么4
并typeid(derived).name()
给出“7derived
”;这是什么7
?为什么
typeid(char).name()
其他内置数据类型只给出第一个字母?功能是什么
type_info::before()
?
感谢您的时间和回答。
解决方案
type_info::name
返回实现定义的类型名称。它不一定与代码中这些类型名称的实际拼写相对应。
GCC 和 Clang 返回重整的名称,因为这就是这些类型名称在内部表示的方式。您可以通过实施名称修饰规则手动对它们进行解构,也可以使用现有工具(例如c++filt
或相应的 API)。
type_info::before
没有直接用处。它的值本质上是任意的,但是是一致的。这使得它可用于将type_info
对象存储在已排序的容器中,例如std::set
,或将它们用作 中的键std::map
。std::type_info::before
这里可以用作排序关系。或者,type_info
可能已经超载operator <
,这可以说是它应该做的。甚至标准库的作者也不明白为什么没有这样做。
以下代码显示了一个type_info::before
以前需要使用的示例。从 C++11 开始,不再需要它,因为您可以改用type_index
密钥。此外,这显然是对运行时类型信息的人为使用:在您根本不会使用的实际代码type_info
中,您将解决函数重载的问题。
#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”.
}
请注意,我们需要存储指针,因为type_info
它不可复制或可移动。
推荐阅读
- php - npm run watch 编译一次后停止编译(laravel 8 homestead + Vue)
- python - 如何将整数转换为特定的字节大小,然后结合起来在套接字上发送
- c# - AggregateException:某些服务无法构建
- linux - 使用 FFMPEG 以非常低的 FPS 进行屏幕捕获(视频截屏)
- xpath - Power Automate - Cloud Flow - 将 xpath 用于父节点属性
- sql-server - SQL Server 作业在调用 SSIS 包时挂起,直到代理重新启动
- php - 在php中更改视频语言
- javascript - 为什么 $(this).attr("id") 在使用 javascript 更改旧属性后获取旧属性
- terraform - 如何让 terragrunt 将 tfvars 文件读入依赖模块
- php - Symfony 5,EasyAdmin 3,如何按角色过滤用户 [ManyToMany 关系 User to UserRoles]