Phil Endecott wrote:
Specifically thinking about strings, there are numerous ways that it could be done. Starting with (1): the obvious sequence of if-else-if: ... (2): binary search using nested switches: ... (3) character-by-character comparison using nested switches: ... (4) converting to a 64-bit integer, for strings of up to 8 characters: ...
Firstly my implementation was never particularly about string in "switch" it is just one of the applications. Secondly, example 3-4 assume additional implementation( can take quite a time to do it right ), it isn't like you have it out of the box, this is exactly what my statement was about( example 1-2 don't count, they are non-scalable ). Lets rather consider something that is more complex: -- Example_1 "Parse file by extension": switch( hash_it( get_file_extention( file_name ) ) ) { case "cpp"HASH: case "cc"HASH: case "c++"HASH: case "cxx"HASH: case "C"HASH: { ... } break; case "hpp"HASH: case "hh"HASH: case "h++"HASH: case "hxx"HASH: case "H"HASH: { ... } break; } // OR // I think this way it is much readable eswitch( get_file_extention( file_name ) ) >> case_( any_from( "cpp", "cc", "c++", "cxx", "C" ) ) >> [&]{...} >> case_( any_from( "h", "hpp", "hh", "h++", "hxx", "H" ) ) >> [&]{...}; // OR // even this could be possible( but not yet implemented ) eswitch( get_file_extention( file_name ) ) >> case_( "cpp", "cc", "c++", "cxx", "C" ) >> [&]{...} >> case_( "h", "hpp", "hh", "h++", "hxx", "H" ) >> [&]{...}; -- Example_2 "Parse HTTP header with Regex": // O_o too much boilerplate if( std::regex_match( line, "^.+ 200 .+$"_r ) ){...} else if( std::regex_match( line, "^.+ 404 .+$"_r ) ){...} else if( std::regex_match( line, "^.+: .+$"_r ) ){...} else { terminate(); } // OR // I think this way your intention is clearer eswitch( line ) >> case_( "^.+ 200 .+$"_r ) >> []{...} // match for "HTTP/1.1 200 OK" case_( "^.+ 404 .+$"_r ) >> []{...} // match for "HTTP/1.1 404 Not Found" case_( "^.+: .+$"_r ) >> [&]{...} >> // match for "key: value" default_ >> []{ terminate(); }; -- Example_2 "match in range of values": // Error prone approach if( value >= 1 && value <= 10 ){ Print("Value in a range[1,10]"); } if( value >= 11 && value <= 20 ){ Print("Value in a range[11,20]"); } else { Print('?'); }; /// OR eswitch( value ) >> case_( _1.in( 1, 10 ) ) >> []{ Print("Value in a range[1,10]"); }
case_( _1.in( 11, 20 ) ) >> []{ Print("Value in a range[11,20]"); }
default_ >> []{ Print('?'); }; // _1 it is lazy index mapping for the params in eswitch
I my opinion "eswitch" looks more readable, more intuitive, less error prone and furthermore it is extensible. P.S. Here https://github.com/rabdumalikov/proposals/blob/master/eswitch_boost_proposal... I had described why I think it is important( just in case you've missed it ).