C++ Logo

std-proposals

Advanced search

Re: [std-proposals] A draft for modern switch

From: Zhao YunShan <dou1984_at_[hidden]>
Date: Wed, 21 May 2025 21:52:29 +0800 (CST)
To Sebastian Wittmeier£º

1.When using switch, there is an implicit requirement that the switched object must have a method for comparing 'equality'. Integers and strings inherently support operator == (either implicitly or explicitly). Therefore, for a custom object, the developer must implement an operator == to make it usable in a switch statement (this is mandatory).
2.As for constexpr hash functions, C++ inherently provides hash methods for integers and strings. However, for custom objects, developers need to define how to compute the hash value, for example£ºstruct object{ int x;}£»size_t hash(const object& o) { return std::hash(o.x); }This requirement, however, is optional. In the absence of a custom hash function implementation, the switch statement may default to jump table-based execution.
3.While match may be more modern, years of muscle memory keep me using switch by default.Moreover£¬most other languages use switch for string comparisons too.

Received on 2025-05-21 13:52:36