代码之家  ›  专栏  ›  技术社区  ›  smerlin

为什么typeid不像sizeof那样是编译时常量

c++
  •  5
  • smerlin  · 技术社区  · 16 年前

    出现这个问题是因为最近我尝试了以下方法:

    template <class T>
    class Foo
    {
        static_assert(typeid(T)==typeid(Bar) || typeid(T)==typeid(FooBar));
    };
    

    我很好奇为什么编译器在编译时知道类型的大小(sizeof),而不知道类型本身(typeid)

    5 回复  |  直到 10 年前
        1
  •  10
  •   smerlin    10 年前

    在处理类型时,您宁愿使用简单的元编程技术:

    #include <type_traits>
    
    template <class T>
    void Foo()
    {
        static_assert((std::is_same<T, int>::value || std::is_same<T, double>::value));
    }
    
    int main()
    {
        Foo<int>();
        Foo<float>();
    }
    

    哪里 is_same 可以这样实现:

    template <class A, class B>
    struct is_same
    {
        static const bool value = false;
    };
    
    template <class A>
    struct is_same<A, A>
    {
        static const bool value = true;
    };
    

    typeid

        2
  •  5
  •   Jason Orendorff Oliver    16 年前

    typeid 表达式是对 std::type_info 对象

    显然,在2008,C++标准委员会 例如示例中的表达式作为常量表达式,就像 sizeof . 但是根据 this comment ,这一变化最终得以恢复。

        3
  •  2
  •   coelhudo    16 年前

    更多信息 here .

        4
  •  1
  •   Mark Ransom    16 年前

    因为 typeid 具有基于对象指针或引用在运行时进行查找的灵活性,它不能返回编译时常量。即使看起来是可以的。 sizeof 没有这样的限制,因为它总是在编译时进行计算。

        5
  •  0
  •   Benoît photo_tom    16 年前

    它在编译时知道类型本身(用它自己的内部语言),但不知道它的类型id(显然是为运行时创建的)。