switch on std::string

This is a discussion on switch on std::string within the C++ Programming forums, part of the General Programming Boards category; I know that this is not possible in standard C++, and I have seen no mention of it in the ...

switch on std::string

I know that this is not possible in standard C++, and I have seen no mention of it in the proposed new standard, but I was thinking it might be cool if they extended the functionality of switch to allow anything that implements the equality operator. this would require that each case needs to implicitly convert to the switched type, which is no big deal for std::string, as you all know, because const char pointers implicitly convert to std::string.

Switch is largely a crutch in programming (often meaning hard-coding code-paths and code reduplication). As such I don't see any reason to widen the usability of switch (as you can already use if...else chains).

Switch is largely a crutch in programming (often meaning hard-coding code-paths and code reduplication). As such I don't see any reason to widen the usability of switch (as you can already use if...else chains).

I agree that if ... else if ... else works just fine, but there are many cases where there are a well-defined set of code paths, and a switch is a more convenient, and in many cases, more easily understood way to achieve that functionality.

I have to agree that it would be a quite valuable addition to the language. I've had once or twice that it'd've been very useful (for instance, parsing something like HTTP, and you have to find out the method, a switch with cases "GET", "POST", etc would imho be better than an if-else sequence. I've seen HTTPd's switch on the length of the method to find it fast enough). But for something like that, it would need at least an operator<, not just an operator=.

That is also why I like switches as well; they can easily be optimized by the compiler. Using lookup tables, or binary searched, or whatever. If-else sequences would be a lot tougher to be optimized to something similar.

That is also why I like switches as well; they can easily be optimized by the compiler. Using lookup tables, or binary searched, or whatever. If-else sequences would be a lot tougher to be optimized to something similar.

Isn't that "easily be optimized by the compiler" part due to the very restrictions that exist in the first place? Like, if the requirement was relaxed to any type for which operator== is defined, then such optimisations would no longer be generally applicable.

Yet, if a programmer really wants to lookup with time comparable to "binary search", a std::map or std::multimap would be appropriate. If a programmer wants constant time lookup, perhaps a hash table with std::tr1::unordered_map or std::tr1::unordered_multimap would be appropriate.