3

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

demo.b
  • 3,299
  • 2
  • 29
  • 29
Ernestas Gruodis
  • 8,567
  • 14
  • 55
  • 117

2 Answers2

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
  • I'm used to it in Java. OK, I will :) – Ernestas Gruodis Mar 27 '14 at 21:03
  • 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