r/cpp•
codingate

Switch-case for user provided datatypes

This issue has been nagging me for a long time. Assuming I'm solely interested in getting switches to work for strings (std::string), would it make sense to the people here to propose something more general aka custom data types in switches or would std::string would be sufficient? I'm asking because using std::map or hashing every item in the case statement doesn't make sense to me. Moreover, this is a "basic" enough task that would help almost every C++ dev and I'm pretty sure a lot of shops have something that emulates this functionality internally.

Currently, even with all C++ features that I can think of, the following is the best I can do to get a switch case on custom datatype (assuming constexpr std::hash<T>::operator(const T&))

switch(auto hash, name = std::tuple{std::hash<std::string>{}, getUserName()}; 
       hash(name)) {
  case hash("cpp11"): std::cout << "Looks promising"; break;
  default:
  case hash("cpp14"): std::cout << "But feels boring";
}

If switch were to take an optional lambda that would change the landscape significantly:

switch(auto name = getUserName(); name; std::hash<std::string>{}) {
  case "cpp11": std::cout << "Looks cleaner"; break;
  default:
  case "cpp14": std::cout << "Beginners can understand it properly";
}

That's of course a pretty lame duck syntax, since it fails to be easy to understand when there's no declaration:

switch(name; hash) { // both variables exist
  case "cpp11": std::cout << "It might be possible to make a different overload"; break;
  default:
  case "cpp14": std::cout << "Treating 'init-statement; condition' as different from 'condition; functor' in language-spec";
}

I saw that something similar was possible with the proposed Pattern Matching Syntax (c++23), however, this isn't really pattern matching and C# has shows that language support for at least "string-literals" is possible and can be faster than if statement chain External link to an old webpage.

Even if there's no support for custom-data types, would it make sense to have C#esque support for string literals in switch statements? Or support for any data structure by using std::hash (making it implicit and removing the need for std::hash if the data type can just be cast into std::size_t, the return type of std::hash)?

Or no? Let's keep using enum and maps and if ladders.....

Posted Dec 9, 2019, 8:06 AM UTC

342
HappyFruitTree•

Hashing alone seems like an unreliable method. What if two strings have the same hash?

I don't think switch will change. We'll just have to wait for pattern matching.

10
MonokelPinguin•

Well, you could detect the hash collisions at compile time, since I'd expect every case to be a compile time constant.

3
HappyFruitTree•

You might have a hash collision with the string that you're switching on.

switch (hash(str))
{
case hash("sun"):
    std::cout << "Nice!\n";
    break;
case hash("rain"):
    std::cout << "Boring!\n";
    break;
default:
    std::cout << "Just a regular day.\n";
    break;
}

I wouldn't want str="snow" to print "Boring!" just because "snow" and "rain" happens to have the same hash value.

4
MonokelPinguin•

Ah, true. I didn't think of that case. Although I think switching on the hash first and then doing a vlaue comparison would still have a runtime benefit in a lot of cases. Although for small switches it is probably most performant to switch on the first character, that differs and then doing a full comparison or something like that.

2
HappyFruitTree•

Yeah, but this becomes tedious if you need to do it by hand.

1
BrangdonJ•

The C# implementation linked does a hash then an operator==() to check.

Obviously the compiler can detect two of the case values having the same hash at compile-time.

2
warieth•

This would give a compile-time error for the identical case values, but you are right. The std::hash implementation is implementation-dependent, so this is not portable code.

1
HappyFruitTree•

This would give a compile-time error for the identical case values

No, since "snow" is not one of the case values.

1
codingateOP•

That's the implicit price of a hash function. You can use 2 hash to reduce the chances but never remove it. Though even with 1, the chances are pretty low but non existent.

0
codingateOP•

Yeah, and any collisions are detected and reported at compile time so there is a way the compiler can add a salt to get the perfect hash function to prevent collisions. We already do this in our implementation (detection and custom salt, not integration with compiler)

1
yuri-kilochekjourneyman template-wizard•

Why do you need to switch directly on strings? Translate them to/from enums on data input/output and switch on those.

3
talvipaivanseisaus•

Because it's

  1. simpler and more readable
  2. less error prone
  3. there's one less enum to worry about

I mean, why do we need different types of variables? Everything could be just made from std::uint8_t.

1
yuri-kilochekjourneyman template-wizard•
  1. less error prone

No, strings are actually more error-prone since a typo won't be detected by the compiler.

  1. simpler and more readable 3) there's one less enum to worry about

These are true, but it's debatable how much that is actually worth.

I mean, why do we need different types of variables?

This is an argument against strings and for enums, since the latter are of different types, unlike the former.

Enums are also faster. With strings constant time switch is possible with perfect hashing, but AFAIK state of the art algorithms require two table lookups (aka cache misses), so that is still slower.

4
talvipaivanseisaus•

You're just as likely to make a typo when creating an enum value from the string, plus a typo in the hypothetical switch could be caught with an default statement. An uninitialized enum could be anything.

Personally I prefer clean and readable code to performance in most cases. Enums would definitely be faster to switch with than strings, that is true, but performance critical parts usually only make up a small amount of code and you could always use an enum in those scenarios. Different tools for different jobs.

1
yuri-kilochekjourneyman template-wizard•

You're just as likely to make a typo when creating an enum value from the string,

Yes, but with enums you only have the opportunity not make a mistake once, when defining the mapping between enums and strings. With strings that happens every time you use switch.

plus a typo in the hypothetical switch could be caught with an default statement. An uninitialized enum could be anything.

Both uninitialized strings and enums are technically UB, but in practice you can catch those with default case for enums as well as strings.

3
codingateOP•

You make a great point about limiting the errors in string translation to one place using enums. But enums have the issue of incompatibility when you add new items, specially when someone somewhere uses the enum for error reporting as well. Enum are a great solution for a lot of time, but... The process of assigning the correct enum needs to be done using, you guessed it, a string switch or map.

I might be narrow sighted here, so I'd like to know your method of assigning the enum variable the correct value based on the string. Maybe there's no need for switch on string. Maybe there is.

1
yuri-kilochekjourneyman template-wizard•

I translate them with frozen::unordered_map.

And enums are compatible (for a certain meaning of compatible, at least no less so than strings) when you add new entries at the end only.

3
codingateOP•

Normally, for enums, we prefer explicit values over implicit so that's not an issue. Add wherever, just put the value for goodness' sake.

People use constexpr unordered maps and ordered maps which sort of means that a standard solution might help. Some of our code contained non constexpr maps which would incur runtime costs for initialisation. That actually resulted in this post. Why should we have to spend our focus on something that could be a language feature? Every project that has user input routinely does this, specially when communication is in JSON.

It's just irritating that such features are missing and based on the reactions, people are lukewarm for such support from the language. There's a std::min and std::midpoint because people make mistakes all the time. There is no such love for switches.

Btw, we are also a big fan of frozen over here actually. For me, it falls into the category of using hashmaps for switching so I thought there might be another method. Frozen has saved us at least a hundred man hours and I'm not exaggerating.

1
BrangdonJ•

std::string is certainly not sufficient for me. I don't use it for strings; I have my own string class. If you mean some more generic notion of strings, like const char *, then maybe.

The first thing that strikes me about that C# implementation is that the chain-of-ifs does not use a binary search. The second thing is that the examples there, and your examples, using strings that only differ in their last character. This is the worst case for operator==() so maybe not the fairest case for comparison.

I would expect if this kind of thing were added to the language, the compiler would be free to choose between implementations based on linear search with operator==(), binary search with operator<=>(), and hashing. That said, it's not something I need myself often, and rarely need it to be performant, and when I do I suspect I'd rather take the time to implement something custom and closer to optimal.

1
codingateOP•

std::map is what looks like s good replacement but it was slow for my use case and we used flatmap instead. Then we replaced it with just the hash.

If char* is supported over std::string, it might indeed be better from a generic code point of view. But i feel unicode crowd sharpening their pitchforks 😅

1
BrangdonJ•

std::map is not a fast way to implement a binary search. It involves a lot of indirection through the nodes. That said, a binary search isn't always faster than a linear one. One issue is that each comparison test has a 50:50 chance of being true, so doesn't benefit from branch prediction.

std::string doesn't support Unicode any better than const char *. Generally stuff like this doesn't care whether the strings are ASCII or UTF8.

3
smuccione•

An ordered_map of string and lambdas would be the way to go here.

In any case a switch like you want would end up being a binary search tree anyway as the best a compiler would be able to do. Maybe it would make a hash out of it (have to be a code shape for a c++ that absent needed to be implemented yet). Worst case is it becomes a bunch of it’s.

You might be able to use some metaprogramming to switch between in-line if’s and a container based on initializer list size.

1
XeverousWorker &amp; Hobbyist with own C++ website under construction•

I don't think there is really any point in extending switch. It recently got the (init; condition) feature and that's all we need. Anything else like changing rules for allowed types/evaluation would get too complex or break some back-compat. Just use else ... if - slighly more code but no break;s required. Both are getting same optimizations if possible.

If there is anything that could help, it's pattern matching.

1
HappyFruitTree•

Both are getting same optimizations if possible.

I wouldn't count on that. https://godbolt.org/z/QZke6q

2
XeverousWorker &amp; Hobbyist with own C++ website under construction•

Interesting ... Clang has no problems with it and MSVC ... likes to jump a lot.

1
TheThiefMasterC++latest fanatic (and game dev)•

I believe the differences are due to the implicit likelihood of branches - if implies that earlier cases are more likely, switch implies equal likelihood.

1
codingateOP•

We have observed hashing to increase performance, specially compared to string comparisons in the if ladder.

Even a trivial binary search gives better performance than the if ladder. If ladder for slightly long strings is hilariously unoptimised code in terms of runtime impact. Hashing and binary search also have the benefit that the cost is almost constant so latency analysis becomes way easier to do since the "branch miss count" remains more or less same for any item in the switch.

If ladder is almost the worst option when the number of items is more than 5. Unordered maps (hashing) are faster at about 3 elements, ordered maps (~binary search) at 5 or 6. It has a real impact when you have data in formats like json.

1
bumblebritches57FoundationIO, OVIA, and occasionally LLVM•

That is literally what C11’s _Generic operator is for.

#define GetUserName(Name)  _Generic(Name, char*:GetUserNameC, short*:GetUserNameS)(Name)

Put that in your header, and define the functions in your source code, boom.

1
adnukator•

OP wants to be able to switch based on the runtime value of a string (or any other currently invalid type in a case statement). _Generic is for function overloading based on types (i.e. what C++ has had forever).

4
bumblebritches57FoundationIO, OVIA, and occasionally LLVM•

Ahh, in that case just use a void pointer and an enum specifying the type at creation time.

1
adnukator•

I don't understand how this is supposed to help. The types of the cases and switch expression are identical and known, e.g.:

std::string somestring = getstring();
switch(somestring)
{
    case "string1"s : std::cout << "a"; break;
    case "string2"s : std::cout << "b"; break;
    case "string3"s : std::cout << "c"; break;
    default: : std::cout << "default"; break;
}

so tagged unions or any variant thereof are an answer to a different question.

1
codingateOP•

Even though I don't think this is what I wish, this is a new thing for me. Thanks for that

2
warieth•

C# has shows that language support for at least "string-literals" is possible and can be faster than if statement chain External link to an old webpage.

C# is a script language, so it doesn't have a separate string implementation. They run an interpreter, and the interpreters string is what they use. The C# compiler/interpreter has built in knowledge about the string type, and it is probably written in an other language and they just copy it into.

Without knowing the string type, there is no better way to do it only as if-(else-if)*-else. The switch-case construct is designed for fast lookup, and the people who want to use it for a completely different purpose wants to hide the implementation details and costs. Usually the support is from people, who only care about the syntax, and don't know anything else about it.

1
BrangdonJ•

If the string type offers hash and equality tests, the compiler doesn't need any more than that. It doesn't have to be a built-in type. If the string can expose the raw bytes as a const char *, then hashing and equality can be written in terms of that.

1
warieth•

The const char* hash is not neccessarily the same as the std::string hash, but the std::string_view might save this idea. Using the c_str is really bad idea, and it's not modern.

I think the compiler could split the cases based on the hash string_view values, then sort it, split to equal ranges, and use operator== for equality tests. There is a problem here: if you don't use a break, then what happens? The compiler could insert jumps for the fallthrough, or the jump in is split? In the original the fallthrough had no extra cost. This is a lot of hard-coded information to the compiler, and for only one type (std::string). I would like to create vectors at compile-time with the string_view, and this could probably replace this.

You question is more about ease of use and to write it short. I think this is not what the switch-case is for, with all case labels and break statements, you have to type anyway. In the cases you can't introduce variables normally, and extending the switch-case can make this worse.

1
BrangdonJ•

Not everyone uses std::string_view. I don't see any reason to hard wire a specific type into the language here. The compiler should be able to use any type that can be hashed and tested for equality. It shouldn't even have to be a string.

It doesn't matter whether the hash used is the same as for std::string, either, as long as it is consistent within the switch.

2
warieth•

The std::string has no constexpr constructor, and the cases use a different type than the switch argument. This needs a conversion to string_view or to const char*, because it uses two different type. The hash value for the two different type can be a mismatch, but the string_view has a guarantee to match the string. The worse solution is to have a const char* support for the switch, and manually convert the string with c_str.

There is already a hard-wired type here, the std::string.

1
chardan965•

I think you might be onto something with compile-time hashing, though certainly there may be some limitations and issues as per the discussion in the thread. Meanwhile, as others have also pointed out... wait for pattern matching. :-)

I know it isn't quite what you're after, but some projects implement libraries for sugared value-based "switching". I've implemented one here (for fun, this has not seen production and is poorly tested, needs conceptification, etc.-- caveat emptor), inspired by LLVM's StringSwitch but allowing for comparable types:

https://github.com/chardan/vswitch

...this amounts to cuter if-statements and surely a number of copies; I wouldn't expect (and haven't measured) performance to be anything close to a real switch.

1
n31415•

You could simplify your code in the following way (this will not remove the problem of hash collisions) with user defined literals

constexpr std::size_t hasher (const std::string &key, std::hash<std::string> hash = {}) {
    return hash(key)();
}

constexpr std::size_t operator ""_h (const char * arg) {
    return hasher(arg); // Do we need an explicit conversion to string?
}

Then your switch would be something like this: switch(hasher(getUserName())) { case "cpp11"_h: //... break; case "cpp14"_h: // }

Note that this is untested, but it should work as is or at least with some minor tweaks (maybe string_view instead of string?).

1