Hi, I saw below thing about switch statement in c++ standard $6.4.2.
Switch statement can take a condition.
The condition shall be of integral type, enumeration type, or of a class type for which a single conversion function to integral or enumeration type exists (12.3). If the condition is of class type, the condition is converted by calling that conversion function, and the result of the conversion is used in place of the original condition for the remainder of this section
I tried below code which is working fine.
class Test
{
public:
operator int() { return 1; }
};
int main()
{
Test obj;
switch(obj)
{
case 1: cout<<"Test class object";
break;
}
}
Is this a better way compared to using a typeid operator to find the object type ?
In switch case way, the overhead is each class should have a unique integer id which will be returned by conversion function.
In typeid way, if we use like typeid(obj) == typeid(Test), if else chain will be lengthy when we have many class types. Code readability decreases. May be its slower as well compared to switch case, as switch case may be implemented like a jump table by Compiler
So, which way is better to find the object type at runtime ?
EDIT: corrected question considering Andrey's comments.