You can use the typeid operator:
#include <typeinfo>
...
cout << typeid(variable).name() << endl;
For static assertions, C++11 introduced decltype
which is quite useful in certain scenarios.
If you have a variable
int k;
You can get its type using
cout << typeid(k).name() << endl;
See the following thread on SO: Similar question
The main difference between C++ and Javascript is that C++ is a static-typed language, wile javascript is dynamic.
In dynamic typed languages a variable can contain whatever thing, and its type is given by the value it holds, moment by moment. In static typed languages the type of a variable is declared, and cannot change.
There can be dynamic dispatch and object composition and subtyping (inheritance and virtual functions) as well as static-dispatch and supertyping (via template CRTP), but in any case the type of the variable must be known to the compiler.
If you are in the position to don't know what it is or could be, it is because you designed something as the language has a dynamic type-system.
If that's the case you had better to re-think your design, since it is going into a land not natural for the language you are using (most like going in a motorway with a caterpillar, or in the water with a car)
Usually, wanting to find the type of a variable in C++ is the wrong question. It tends to be something you carry along from procedural languages like for instance C or Pascal.
If you want to code different behaviours depending on type, try to learn about e.g. function overloading and object inheritance. This won't make immediate sense on your first day of C++, but keep at it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With