Boost logo

Boost :

From: Phil Endecott (spam_from_boost_dev_at_[hidden])
Date: 2019-11-10 14:16:09


vigosslive2_at_[hidden] wrote:
> I wrote a library *eswitch* which provides enhanced functionality for* C++
> switch*.
> Please take a look and leave your comments.

I've had a look at your docs, and I don't immediately find anything
that explains how it works.

Specifically thinking about strings, there are numerous ways
that it could be done. Starting with

switch (s) {
  case "aa" : f(); break;
  case "ab" : g(); break;
  case "xy" : h(); break;
}

that can be transformed into:

(1): the obvious sequence of if-else-if:

if (s == "aa") f();
else if (s == "ab") g();
else if (s == "xy") h();

(2): binary search using nested switches:

switch (s <=> "ab") {
  case -1: switch (s <=> "aa") {
             case -1: break;
             case 0: f(); break;
             case 1: break;
           }
           break;
  case 0: g();
           break;
  case 1: switch (s <=> "xy") {
             case -1: break;
             case 0: h(); break;
             case 1: break;
           }
           break;
}

(3) character-by-character comparison using nested switches:

switch (s[0]) {
  case 'a': switch (s[1]) {
              case 'a': switch (s[2]) {
                          case 0: f(); break;
                        }
              case 'b': switch (s[2]) {
                          case 0: g(); break;
                        }
            }
  case 'x': switch (s[1]) {
              case 'y': switch (s[2]) {
                          case 0: h(); break;
                        }
            }
}

(4) converting to a 64-bit integer, for strings of up to 8 characters:

switch (cast_to_uint64(s)) {
  case "aa"TOINT: f(); break;
  case "ab"TOINT: g(); break;
  case "xy"TOINT: h(); break;
}

(5) hashing, and then checking:

switch (hash(s)) {
  case "aa"HASH: if (s=="aa") f(); break;
  case "ab"HASH: if (s=="ab") g(); break;
  case "xy"HASH: if (s=="xy") h(); break;
}

I'm sure there are other possibilities.

Regarding syntax, there isn't much wrong with just writing the
sequence of if-else-ifs. In particular, when the next person comes
along and needs to understand this code, which of the following
will they prefer:

if (s == "aa") f();
else if (s == "ab") g();
else if (s == "xy") h();

or:

eswitch(s) >>
  case_("aa") >> []{ f(); } >>
  case_("ab") >> []{ g(); } >>
  case_("xy") >> []{ h(); };

I can see no benefit to your version, UNLESS it results in a more
efficient implementation than the if-else-if version.

Regards, Phil.


Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk