Search code examples
c++switch-statementcomparisonc++17syntactic-sugar

How to implement universal switch/case, which can work for general C++ types as well and syntactically similar?


In C/C++, switch/case compares only an integral type with a compile time constants. It's not possible to use them to compare user/library defined types like std::string with runtime values. Why the switch statement cannot be applied on strings?

Can we implement look-a-like switch/case which gives similar syntactic sugar and serves the purpose of avoiding plain if/else comparisons.


struct X { 
  std::string s;
  bool operator== (const X& other) const { return s == other.s; }
  bool operator== (const std::string& other) const { return s == other; }
};

In nutshell, one should be able to run this switch/case, if there is an operator== defined for a type X. i.e.:

X x1{"Hello"}, x2{"World"};
switch(x1)
{
  // compare literal or any different type for which `==` is defined
  case "Hello": std::cout << "Compared 'Hello'\n"; break;     
  // cases/default appear in between and also can fall-through without break
  default:      std::cout << "Compared 'Default'\n"; 
  // compare compiletime or runtime created objects
  case x2:    { std::cout << "Compared 'World'\n"; break; }
}

I know above is not possible as it is. But anything similar looking will be good.
This question is inspired by a way demonstrated in this blogspot: Fun with switch statements.


Solution

  • Implentation:

    #define CONCATE_(X,Y) X##Y
    #define CONCATE(X,Y) CONCATE_(X,Y)
    #define UNIQUE(NAME) CONCATE(NAME, __LINE__)
    
    #define MSVC_BUG(MACRO, ARGS) MACRO ARGS
    #define NUM_ARGS_2(_1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, _14, TOTAL, ...) TOTAL
    #define NUM_ARGS_1(...) MSVC_BUG(NUM_ARGS_2, (__VA_ARGS__))
    #define NUM_ARGS(...) NUM_ARGS_1(__VA_ARGS__, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1)
    #define VA_MACRO(MACRO, ...) MSVC_BUG(CONCATE, (MACRO, NUM_ARGS(__VA_ARGS__)))(__VA_ARGS__)
    
    #define switch_(X) for(struct { static_assert(not std::is_pointer<decltype(X)>::value, "No Pointers!"); \
                  const decltype(X)& VALUE_; enum { CASES, DEFAULT, COMPARED } IS_ = CASES; } VAR_{X}; \
                           VAR_.IS_ != VAR_.COMPARED; \
                           VAR_.IS_ == VAR_.DEFAULT or (VAR_.IS_ = VAR_.COMPARED))
    
    #define default_ {}} if(VAR_.IS_ == VAR_.COMPARED or VAR_.IS_ == VAR_.DEFAULT or \
                            ((VAR_.IS_ = VAR_.DEFAULT) and false)) \
                         { VAR_.IS_ = VAR_.COMPARED; CONCATE(default,__LINE__)
    
    #define case_(...) VA_MACRO(case_, __VA_ARGS__)
    #define case_1(X)    {}} if(VAR_.IS_ == VAR_.COMPARED or VAR_.VALUE_ == X) \
                             { VAR_.IS_ = VAR_.COMPARED; CONCATE(case,__LINE__)
    #define case_2(X,OP) {}} if(VAR_.IS_ == VAR_.COMPARED or VAR_.VALUE_ OP X) \
                             { VAR_.IS_ = VAR_.COMPARED; CONCATE(case,__LINE__)
    

    Usage:

    X x1{"Hello"}, x2{"World"};
    switch_(x1)
    {{ // <--- MUST
      case_("Hello"):   std::cout << "Compared 'Hello'\n"; break;
      default_:         std::cout << "Compared 'Default'\n";
      case_(x2):      { std::cout << "Compared 'World'\n"; break; }
      case_("World"): { std::cout << "Duplicate 'World' again!\n"; break; } // duplicate
    }}
    

    Notes:

    • Purpose for {{ }} -- is to fix a scenario, where 2 or more statements under case_ are appearing without enclosing user provided {}. This could have resulted in certain statements always executing irrespective of whichever case_ is true.
    • Higher the default_ placed, better the runtime performance. Putting it lower may make more comparisons when no cases are valid.
    • Duplicate cases will compile but only the 1st case will be executed. This duplicate case issue can be fixed/checked by producing a runtime abort(), if one is ready to go through every case more than once.
    • If one is ready forego syntactic sugar of colon :, i.e. case(X) instead of case(X):, then the CONCATE macro is not needed. Retaining colons usually gives compiler warning of unused labels (-Wunused-label)
    • This utility can be extended for other comparisons such as <, >=, !=, or any such operator; For that we have to add extra argument to switch_ macro; e.g. OP and that has to be placed in case_ macro as VAR_ OP X
    • For C++03 compatibility, use make_pair inside the for loop after declaring a struct UNIQUE(Type) { enum { ... }; };
    • Arrays and string pointer can be compared with below utility:

    template<typename T>
    struct Compare
    {
      const T& this_;
      template<typename T_, size_t SIZE>
      bool
      operator== (const T_ (&other)[SIZE]) const
      {
        static_assert(std::is_same<decltype(this_), decltype(other)>::value, "Array size different!");
        return ::memcmp(this_, other, SIZE);
      }
    };
    template<>
    struct Compare<const char*>
    {
      const char* const this_;
      bool operator== (const char other[]) const { return (0 == ::strcmp(this_, other)); }
    };
    #define COMPARE(X) Compare<decltype(X)>{X}
    

    Usage: switch_(COMPARE(var)) {{ }}.

    Demo