+ 1

How to work with different types in switch statement?

For eg., the case value must be in both integer and character type.. switch(value) case 1 : break; case 'a' : break; Is this possible.. ? nor how use it..?

24th May 2018, 2:24 PM
Kumaresan L
Kumaresan L - avatar
1 Respuesta
+ 4
It is possible, but the requirement is that value must be convertible to the different types at compile time and that value is an integral type, e.g int, char, long long. but not double or string For example lets say value is an int. 1 is an int, no cast is needed so it is accepted. 'a' is a char, a char is basically an int already, it gets casted to 97, which is the int equivalent. So your switch will compile. We can pull it off even with custom types, but again, said type must be convertible to each type used in the switch and be an integral type, which a custom type is not, unless we cast it. Lets define our own class: class MyClass { public: constexpr MyClass(int v):value(v){} constexpr operator int() const { return value; } private: int value; }; The constexpr (C++11 feature) is the important part here, it says this function can be evaluated at compile time ( which a switch requires ). The operator int() says that this type is convertible to an int. Now the class is compile time and is convertible to an integral type, which the switch requires. Therefore the following program compiles: MyClass n = 0; switch( n ) { // if n = 1 case 1: std::cout << "1\n"; break; // if n = 97 case 'a': std::cout << "a\n"; break; // if n = 0 case MyClass(0): std::cout << "0\n"; break; } But yea, not the recommend way of doing things, might be important to know though :)
24th May 2018, 2:47 PM
Dennis
Dennis - avatar