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

回眸只為那壹抹淺笑 提交于 2021-01-27 22:57:25

问题


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.


回答1:


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




回答2:


You can't get around the fact that the switch cases must be constexpr integrals so case x2: will not work. It must be constexpr.

One way to emulate switching on constexpr strings could be to use a constexpr hashing function.

Example:

#include <iostream>

// boilerplate - any constexpr hashing function would do
inline constexpr uint64_t ror64(uint64_t v, int r) {
    return (v >> r) | (v << (64 - r));
}

inline constexpr uint64_t rrmxmx2(uint64_t v) {
    v ^= ror64(v, 27) ^ ror64(v, 52);
    v *= 0x9fb21c651e98df25UL;
    v ^= ror64(v, 27) ^ ror64(v, 52);
    v *= 0xc20bf31a8f5694c9UL;
    return v ^ (v >> 28);
}

class Checksum {
    static constexpr uint64_t INC1 = 0x3C6EF372FE94F82BUL; // sqrt(5)
    static constexpr uint64_t INC2 = 0xA54FF53A5F1D36F1UL; // sqrt(7)

    uint64_t words = 0;
    uint64_t s[4] = {INC1, INC2, INC1, INC2};

public:
    constexpr Checksum(const uint64_t S[4], uint64_t Words) :
        words(Words), s{S[0], S[1], S[2], S[3]} {}
    constexpr Checksum() {}
    constexpr Checksum(const char* str) {
        while(*str != '\0') {
            update(*str);
            ++str;
        }
    }

    bool operator==(const Checksum& rhs) const {
        return words == rhs.words && s[0] == rhs.s[0] && s[1] == rhs.s[1] &&
               s[2] == rhs.s[2] && s[3] == rhs.s[3];
    }
    inline bool operator!=(const Checksum& rhs) const { return !(*this == rhs); }
    constexpr void update(uint64_t w) {
        uint64_t tmp = s[0] + rrmxmx2(s[1] + (s[2] ^ s[3]));
        s[0] = s[1];
        s[1] = s[2];
        s[2] = s[3] + ++words;
        s[3] = tmp + w;
    }
    constexpr size_t finalize() {
        for(int i = 0; i < 64; ++i) {
            uint64_t tmp = s[0] + rrmxmx2(s[1] + (s[2] ^ s[3]));
            s[0] = s[1];
            s[1] = s[2];
            s[2] = s[3] + i;
            s[3] = tmp;
        }
        return s[0];
    }
};

constexpr size_t checksum(const char* str) {
    return Checksum(str).finalize();
}
// end of boilerplate

int main() {
    std::string word;
    size_t hash;

    do {
        std::cout << "enter a word: ";
        std::cin >> word;

        hash = checksum(word.c_str());

        switch(hash) {
        case checksum("foo"):
            std::cout << "excellent\n";
            break;
        case checksum("bar"):
            std::cout << "very good\n";
            break;
        case checksum("baz"):
            std::cout << "well done\n";
            break;
        case checksum("secret"):
            std::cout << "extremely gifted\n";
            break;
        default:
            std::cout << "invalid word\n";
        }
    } while(hash != checksum("quit"));
}


来源:https://stackoverflow.com/questions/58216845/how-to-implement-universal-switch-case-which-can-work-for-general-c-types-as

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!