c++11 - type_traits 如何在编译时知道所有关于多态性的信息
问题描述
我正在学习如何使用type_traits
C++11,有人告诉我这type_traits
在编译时有效。
我真的很惊讶。我做了如下测试:
class A {virtual void foo();};
class B : public A {};
constexpr bool b = std::is_base_of<A, B>::value;
constexpr bool bb = std::is_polymorphic<A>::value;
constexpr bool bb2 = std::is_polymorphic<B>::value;
int main()
{
return 0;
}
我用命令编译这段代码:g++ -std=c++11 main.cpp -g
并得到一个二进制文件a.out
。
然后我执行命令objdump -dj .rodata a.out
并得到输出:
./a.out: file format elf64-x86-64
Disassembly of section .rodata:
0000000000000830 <_IO_stdin_used>:
830: 01 00 02 00 ....
0000000000000834 <_ZStL19piecewise_construct>:
...
0000000000000835 <_ZL1b>:
835: 01 .
0000000000000836 <_ZL2bb>:
836: 01 .
0000000000000837 <_ZL3bb2>:
837: 01 .
好的,type_traits
在编译时确实有效。
但是怎么做?或者这是否意味着 c++ 编译器可以在编译时获取所有多态信息?我一直认为多态性信息都是关于运行时的东西......
解决方案
多态类型是其实例可以表现出多态行为(虚函数调用、类型擦除、RTTI 等)的类型。行为本身发生在运行时,但这种可能性在编译时已经知道——如果只是因为编译器必须生成启用它的内部数据结构(vtables 等)。
例如,给定两种神秘类型X
和Y
:
void check(X const &x) {
if(dynamic_cast<Y *>(&x))
std::cout << "We have a Y!\n";
}
...条件将在运行时通过 iffY
是 的动态类型之一x
,但函数本身仅在 有效时才会编译dynamic_cast
,即 ifX
和Y
是多态类型。
推荐阅读
- java - @RestController 是否有办法在没有 Servlet 和 HttpServletRequest 的情况下进行过滤或拦截?
- node.js - 使用 package-lock.json 为特定节点版本安装 npm 依赖项
- android - 如何解决在 Flutter 中启动应用程序时无法在 C:\Users\iampr\AppData\Local\Android\sdk 中找到带有哈希字符串 'android-27' 的目标
- php - ACF WP_Query 按分类字段筛选
- javascript - 我想用 (new Promise) 将数据存储在变量中?javascript
- html - 跨单元格组在 HTML 表格中居中文本
- javascript - 在没有 onChange 的情况下反应文本表单字段
- php - 如何通过 PHP 登录到另一个站点并下载站点中的特定页面
- node.js - gmail api 无法正常发送带附件的电子邮件
- javascript - 所有重要的网站 Prestashop 内容都必须在关闭 js 并以纯 html 形式提供的情况下可供搜索机器人使用