Search code examples
c++pointersruntimetypeidtypeinfo

How to check if a typeid is a pointer at runtime?


In C++, is it possible to determine if a type_info object describes a pointer at runtime? For example,

char a1;
char *a2;

const std::type_info &ti1 = typeid(a1);
const std::type_info &ti2 = typeid(a2);

std::cout << is_pointer(ti1) << std::endl;
std::cout << is_pointer(ti2) << std::endl;

would print false for ti1 and true for ti2.

Obviously one could do std::is_pointer<decltype(a1)>::value but that requires that we have access to the variable identifier a1. What if we only have access to its typeid ti1?


Solution

  • typeid() gives you a std::type_info object. That's all.

    As you can see in this documentation, type_info doesn't really tell you a lot. Pretty much anything of use there is "implementation defined".

    And, there isn't anything there that tells you, authoritatively, whether the type is a pointer of some kind.

    "Implementation defined" means that your C++ compiler defines what that means. It's very much possible that if you were to consult your compiler's documentation, you will find some additional explanation of what name() returns, and it may very well be possible to trivially determine, from name(), whether the type is a pointer. How, and in what way, depends entirely on your compiler and, of course, it will be completely non-portable.