Search code examples
c++stringc++11stdstdstring

Is the answer given for "Why switch statement cannot be applied on strings?" still true, even with C++11/14?


I came across this question: Why switch statement cannot be applied on strings? and wonder if the answer:

The reason why has to do with the type system. C/C++ doesn't really support strings as a type. It does support the idea of a constant char array but it doesn't really fully understand the notion of a string.

still holds true, even with std:string within C++11/14. Is there an alternative to having severals else if(...)'s?


Solution

  • Yes, it still holds.
    As stated here, the condition can be:

    any expression of integral or enumeration type, or of a class type contextually implicitly convertible to an integral or enumeration type, or a declaration of a single non-array variable of such type with a brace-or-equals initializer.

    I came across that question a couple of days ago, and I guess you can figure out an alternative solution for the if/else chain from there.
    It mostly depends on your actual problem if it's possible, anyway the basic idea is to use a map of callable objects from which to access using your objects (strings in this case) as a key. That map has to be filled somehow before to use it, of course.