C++ Logo

std-proposals

Advanced search

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

From: Thiago Macieira <thiago_at_[hidden]>
Date: Tue, 27 May 2025 10:23:22 -0300
On Monday, 26 May 2025 12:14:14 Brasilia Standard Time Arthur O'Dwyer via Std-
Proposals wrote:
> So (this is a probably-rhetorical question directed at @ZhaoYunshan) what
> API would you have to require of the author of WrappedInt in order to make
> their type "switch-able"?

I'm going to guess that for:
  switch (typeAexpression) {
  case typeBvalue:

we need that TypeB be constexpr constructible and destructible and that there
is a weak-ordering, constexpr operator<=>(TypeA, TypeB). An equality operator
alone won't suffice, because then the order of case labels would matter, which
seems ill-advised to me. Maybe the ordering can be partial, but I don't know
for sure.

With this, the compiler can sort the entries in the case labels and create a
binary search, with an average of O(log n) comparisons.

Do note that this may not be the most optimal. For a large string table, what
I'd manually do is switch on the first letter, which *can* often be placed in a
jump table, and then perform comparisons from the second letter onwards. For
an average of 4 strings per first letter and about 20 different first letters
(~160 strings total), that would be 1 jump plus an average of 2 comparisons,
versus the average of 7.3 comparisons with the plain O(log n) binary search.
But I have no clue how to teach the compiler on how to do the first-letter-
switching automatically.

-- 
Thiago Macieira - thiago (AT) macieira.info - thiago (AT) kde.org
  Principal Engineer - Intel Platform & System Engineering

Received on 2025-05-27 13:23:28