C++ Logo

std-proposals

Advanced search

Re: [std-proposals] Switch on strings

From: Frederick Virchanza Gotham <cauldwell.thomas_at_[hidden]>
Date: Sun, 26 Feb 2023 22:58:03 +0000
On Sun, Feb 26, 2023 at 10:47 PM Frederick Virchanza Gotham
<cauldwell.thomas_at_[hidden]> wrote:
>
> So if a 'switch' statement could work with strings, would the strings
> need to be compile-time const arrays of char's?


Look what I've done on GodBolt:

      https://godbolt.org/z/1141ov8PT

And here it is copy-pasted:

#include <string_view>

constexpr unsigned long long MyHasher(std::string_view const arg)
{
    unsigned long long retval = 0u;

    for ( auto const &c : arg ) retval += c;

    return retval;
}

consteval auto compile_time(auto arg)
{
    return arg;
}

int main(int const argc, char **const argv)
{
    switch ( MyHasher(argv[0]) )
    {
    case compile_time(MyHasher("Monkey")):
    case compile_time(MyHasher("Donkey")): ;
    }
}

The C++ core language could be changed so that the switch statement in
'main' could be written in shorthand as:

    switch<MyHasher> ( argv[0] )
    {
    case "Monkey":
    case "Donkey": ;
    }

Received on 2023-02-26 22:58:15