首页 > 解决方案 > type_traits 如何在编译时知道所有关于多态性的信息

问题描述

我正在学习如何使用type_traitsC++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++ 编译器可以在编译时获取所有多态信息?我一直认为多态性信息都是关于运行时的东西......

标签: c++11polymorphismruntimetypetraitscompile-time

解决方案


多态类型是其实例可以表现出多态行为(虚函数调用、类型擦除、RTTI 等)的类型。行为本身发生在运行时,但这种可能性在编译时已经知道——如果只是因为编译器必须生成启用它的内部数据结构(vtables 等)。

例如,给定两种神秘类型XY

void check(X const &x) {
    if(dynamic_cast<Y *>(&x))
        std::cout << "We have a Y!\n";
}

...条件将在运行时通过 iffY是 的动态类型之一x,但函数本身仅在 有效时才会编译dynamic_cast,即 ifXY是多态类型。


推荐阅读