Is there any alternative to use switch
using a wstring
in C++? In Java it's no problem - switch
accepts String
.
Asked
Active
Viewed 2,904 times
3

demo.b
- 3,299
- 2
- 29
- 29

Ernestas Gruodis
- 8,567
- 14
- 55
- 117
-
1Yep, an if/else block. – enhzflep Mar 27 '14 at 21:01
-
Yes, I know, but it's not very convenient.. – Ernestas Gruodis Mar 27 '14 at 21:02
-
There is no switch on strings in C++. The language does not support that. – Marius Bancila Mar 27 '14 at 21:02
-
Indeed. However, alternatives are often less convenient - as is the case (pardon the pun) here. :) – enhzflep Mar 27 '14 at 21:03
-
Nothing nearly as simple as a language supported switch statement, but take a look at http://stackoverflow.com/questions/4165131/c-c-switch-for-non-integers – manlio Mar 27 '14 at 21:06
2 Answers
8
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
.

Bathsheba
- 231,907
- 34
- 361
- 483
-
-
IMHO switching on strings in Java was the start of a few terrible decisions. Having default implementations in interfaces (Java 8) trumps it though. Before then, that terrible date library. And whose idea was it to zero-base the months? – Bathsheba Mar 27 '14 at 21:05
-
@Bathsheba: zero-based months were already used in C, so it might be K&R. To be honest, I never liked that idea either, somebody explained that zerobased month was more convenient to index month name arrays. – stefaanv Mar 27 '14 at 21:21
1
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).

Chnossos
- 9,971
- 4
- 28
- 40