Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++: alternative to switch using wstring

Is there any alternative to use switch using a wstring in C++? In Java it's no problem - switch accepts String.

like image 511
Ernestas Gruodis Avatar asked Oct 15 '25 08:10

Ernestas Gruodis


2 Answers

In C++ you can only switch on integral types. That's by design and to be able to switch on strings would complicate (or break) the language.

There are flashy alternatives such as creating maps of strings to numbers and switching on the latter, but they only obfuscate.

Don't fight the language. Just use if, else if and else.

like image 98
Bathsheba Avatar answered Oct 16 '25 22:10

Bathsheba


If you have only a few cases, then go with if-else blocks.

With more than 5 cases, i'd use a std::unordered_map (#include <unorered_map> or #include <tr1/unordered_map>) with std::wstring as keys and std::function as value (this way you can use lambda if you don't want to write lone functions).

like image 26
Chnossos Avatar answered Oct 16 '25 20:10

Chnossos



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!