+ 1

Is there a way to check that a variable is an int?

Had a look at the <typeinfo> and <type_traits> header files, but the only way i could see to do it was to use a rouge integer to compare against... #include <iostream> #include <typeinfo> using namespace std; int main() { int a = 7; //rogue number for use in typeid to test against..is there some other way? int myint = 40; if(typeid(myint).name() == typeid(a).name()){ cout << "It is an integer"; } return 0; } Is there some other way?

31st Aug 2019, 7:26 PM
rodwynnejones
rodwynnejones - avatar
7 odpowiedzi
+ 3
x if( (int)(x) == x) cout<<"yes"; else cout<<"no";
31st Aug 2019, 8:09 PM
CHERIEF Houcine Abdelkader
CHERIEF Houcine Abdelkader - avatar
+ 2
I have once stumbled over this and found it helpful. I hope you'll find what you need. https://stackoverflow.com/questions/1986418/typeid-versus-typeof-in-c
31st Aug 2019, 7:43 PM
HonFu
HonFu - avatar
+ 2
Honfu Had a scan of your link..but can't find anything that does what I was after. In python you have isinstance function. in c++ you have 'is_class' and pass a class name to it and it will return true or false, but is_intergral only takes a type name e.g 'int' rather than on object of that type e.g '5'. Thanks anyway.
31st Aug 2019, 8:27 PM
rodwynnejones
rodwynnejones - avatar
+ 2
Use decltype to get the type. if( std::is_integral<decltype(5)>::value ) { std::cout << "integral\n"; } But you really do not need this because 5 will always be an int, 5.f will always be a float and 5.0 will always be a double. I've never needed this other than with templates.
31st Aug 2019, 8:30 PM
Dennis
Dennis - avatar
+ 2
To be honest, I can remember why I need to do this, it was a small project I was working on (for myself) a few months back. But.... can you pass a variable of type 'int' into it rather than a constant, '5' in you example. Thanks for the decltype suggestion, I'll look more into it.
31st Aug 2019, 8:46 PM
rodwynnejones
rodwynnejones - avatar
+ 2
int x; if( std::is_integral<decltype( x )>::value ) FYI, integral and int are not the same, the above also returns true for long long or char, for example. std::is_same<int, decltype( x )>::value would return true just for an int type.
31st Aug 2019, 8:49 PM
Dennis
Dennis - avatar
+ 1
Why would you even need to? A variable with the type int will always be an int. This isn't python or js. The only case I can think of is in combination with templates where you want the template to accept only integrals, for example. In that case you can combine std::enable_if and std::is_integral for all integral types or std::enable_if and std::is_same<int,T> just for ints.
31st Aug 2019, 8:11 PM
Dennis
Dennis - avatar