2
I’m using the operator typeid
to check conditions, where I do the following basic test:
int main()
{
cout << (typeid(int) == typeid('abc')) << endl; //TRUE
cout << (typeid(int) == typeid(100)) << endl; //TRUE
cout << (typeid(int) == typeid(100.40)) << "\n" << endl; // FALSE
cout << (typeid(float) == typeid('abc')) << endl; // FALSE
cout << (typeid(float) == typeid(100)) << endl; // FALSE
cout << (typeid(float) == typeid(100.40)) << "\n" << endl; // FALSE
cout << (typeid(char) == typeid('a')) << endl; //TRUE
cout << (typeid(char) == typeid('ab')) << endl; // FALSE
cout << (typeid(char) == typeid(100)) << endl; // FALSE
cout << (typeid(char) == typeid(100.40)) << endl; // FALSE
return 0;
}
But I couldn’t understand the true
and false
for certain conditions, such as:
cout << (typeid(int) == typeid('abc')) << endl; //TRUE
cout << (typeid(float) == typeid(100.40)) << "\n" << endl; // FALSE
cout << (typeid(char) == typeid('ab')) << endl; // FALSE
Questions in doubt:
- to) If a
char
is also the typeint
, how to differentiate aint
of achar
? - b) Why
typeid(float) == typeid(100.40)
is nottrue
? - c) Why
typeid(char) == typeid('ab')
is nottrue
?
The syntax is c++, but the idea here would be to understand the response of this function, so I inserted the c tag as well. Well, how do I stop at runtime to compare the primitive types? Add your answer that I apply the same as the correct one.
– user148754
Why do you want to do this? I saw no need.
– Maniero
The intention is to make use of conditions in case the type inserted at runtime is different from the one I entered it returns an error, but it is only for learning even.
– user148754
This is impossible to do. The type is set at compile time so it cannot be different at runtime. I don’t think you understand what this operator is for. So I stress, it’s only useful for polymorphic comparisons, which is not the case, this is the only chance of the type being different at runtime. Don’t try to do something that doesn’t need to be done and it makes no sense to do it.
– Maniero
Okay, I get it, so I have to use the famous switch to analyze the input from Cin? To check if it really is a number or a char? I’m trying to do something elegant for this, which suggests?
– user148754
No, no need, if you declare the variable as
char
is achar
, declare itself as aint
is aint
, It doesn’t change anything and you already know what kind it is when you’re coding, you don’t need any of this. The typing is already defined in your code, what you want to do makes no sense.– Maniero