比较两个 typeid 表达式是否相等时出现编译器错误

Compiler error when comparing two typeid expressions for equality

关于这段来自培训视频的代码:

#include <iostream>

template<typename T>
struct MyStruct {
   T data;
};

int main(void)
{
   MyStruct<int> s;
   s.data = 2;
   assert(typeid(s.data) == typeid(int));
}

我收到这个编译器错误:

class_templates.cpp:12:26: error: invalid operands to binary expression ('const std::type_info' and 'const std::type_info')
   assert(typeid(s.data) == typeid(int));
          ~~~~~~~~~~~~~~ ^  ~~~~~~~~~~~

编译:

clang++ -std=c++14 class_templates.cpp

编辑:如果我用 g++ 编译,我会得到一个更好的错误:

class_templates.cpp:14:20: error: must #include <typeinfo> before using typeid
    assert(typeid(s.data) == typeid(int));

必须使用#include <typeinfo>才能使用typeid(),否则您的程序格式错误。

另见: