Compiler error when comparing two typeid expressions for equality

1.6k views Asked by At

On this code which comes from a training video:

#include <iostream>

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

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

I get this compiler error:

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));
          ~~~~~~~~~~~~~~ ^  ~~~~~~~~~~~

compiled with:

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

Edit: Had I compiled with g++ I would have gotten a better error:

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

There are 1 answers

0
Remy Lebeau On BEST ANSWER

You must use #include <typeinfo> in order to use typeid(), otherwise your program is ill-formed.

Also see:

Why do I need to #include <typeinfo> when using the typeid operator?