Is there any alternative to use switch
using a wstring
in C++? In Java it's no problem - switch
accepts String
.
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
.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With