While C++ programmers are used to its poor ergonomics, getting the type of a variable in C++ is a surprisingly convoluted process.
Luckily, we don't often find ourselves in need of guessing a type, but when we do, we are up against one of the original basic traits of C++, its mangling of identifiers, that is, the names of functions and types.
During its first steps, C++ was just an abstraction layer over C. But, unlike C, C++ allows function overload, so functions could share names as long as they don't share signature (the types of its input parameters). C++ also allows templates so fundamentally different types could have, on a surface level, the same name.
Bjarne Stroustrup wrote a C++ to C compiler and then made use of available C compilers for the final translation to machine code. So Bjarne had to use the available C linkers at the time, which understood functions and types as symbols and the only identifier for a symbol was its name, which was fine for C, but not for C++. Hence, name mangling. To this day C++ will modify the name of all its types and functions in a platform dependent way (C++ standard allows this), so the linker doesn't think there was a redefinition error.
The implication of all of this is that even if we are able to check the type of our variables, that type would look like gibberish for us since, as you can imagine, automatic machine mangling does not look nice. And to make things worse, the mangler is not unique to C++, so same types will get different mangled names in different platforms.
To deal with all of this we're going to need 2 libraries, a standard one (
typeinfo) to get our types,
and one from boost to demangle them (
boost/core/demangle.hpp). You can check this godbolt to see the end result.
Finally, I've also retrieved the necessary boost headers to get this same functionality in my projects without the need of installing boost,
which would be overkill for our needs. Here's the github repo with the
typeof header-only library.
It's based on boost's license since it's basically a very small collection of boost headers + 1 header (
typeof.hpp) with a convenience function.
I've also added a
CMakeLists.txt so you can add it to your project just by adding the folder into you project's folder and these 2 lines in your main
If you clone the repo you'll see how it all works.
Shortly after doing all of this, I found nameof which does the same thing and more, and is also header-only, so it's a better solution in every aspect.