Search code examples
c++g++constantsvolatilertti

type_info doesn't account for cv qualifiers: is this right?


Is it the correct behaviour or is it a quirk of g++4.5 that this code prints 1?

#include <iostream>
#include <typeinfo>
using namespace std;

int main(){
    struct A{};
    cout<<(typeid(A)==typeid(const A)&&typeid(A)==typeid(const volatile A)&&typeid(A)==typeid(volatile A));
}

I thought that types differing for cv-qualifiers were threated as very distinct types, even though less cv-qualified types could be implicitly cast to more cv-qualified types.


Solution

  • typeid ignores cv qualifiers, as per the C++ standard (taken from §5.2.8 from ISO/IEC 14882:2003) :

    The top-level cv-qualifiers of the lvalue expression or the type-id that is the operand of typeid are always ignored. [Example:

    class D { ... };
    D d1;
    const D d2;
    
    typeid(d1) == typeid(d2);       // yields true
    typeid(D) == typeid(const D);   // yields true
    typeid(D) == typeid(d2);        // yields true
    typeid(D) == typeid(const D&);  // yields true
    

    —end example]

    So, the result you're seeing is expected.