如何实现通用开关/大小写,该开关/大小写也可以在常规C ++类型上运行并且在语法上相似? [英] How to implement universal switch/case, which can work for general C++ types as well and syntactically similar?

查看:95
本文介绍了如何实现通用开关/大小写,该开关/大小写也可以在常规C ++类型上运行并且在语法上相似?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在C/C ++中, switch/case 仅将整数类型与编译时间常数进行比较.不能使用它们将用户/库定义的类型(如 std :: string )与运行时值进行比较.为什么switch语句不能应用于字符串?

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?

我们是否可以实现相似 switch/case ,它给出类似的语法糖,并避免普通的 if/else 比较.

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; }
};

简而言之,如果为类型 X 定义了 operator == ,则应该能够运行此 switch/case .即:

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; }
}

我知道上面是不可能的.但是任何类似的外观都会很好.
这个问题的灵感来自以下 blogspot:带有switch语句的乐趣

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.

推荐答案

图示:

#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__)

用法:

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
}}

注意:

  • 使用 {{}} 的目的是解决以下情况:在 case _ 下出现2条或更多条语句而没有包含用户提供的 {} .这可能导致某些语句始终执行,而与 case _ 的正确性无关.
  • 放置的 default _ 越高,运行时性能越好.如果没有有效的案例,将其降低可以进行更多的比较.
  • 重复的案例将被编译,但是仅第一个案例将被执行.如果准备好多次处理每种情况,可以通过生成运行时 abort()来解决/检查此重复的案例问题.
  • 如果已经准备好放弃冒号:的语法糖,即 case(X)而不是 case(X):,则不需要 CONCATE 宏.保留冒号通常会向编译器警告未使用的标签( -Wunused-label )
  • 可以将此实用程序扩展用于其他比较,例如< > = != 或任何此类运算符;为此,我们必须在 switch _ 宏中添加额外的参数;例如 OP ,并且必须作为 VAR_ OP X
  • 放在 case _ 宏中
  • 出于C ++ 03的兼容性,在声明 struct UNIQUE(Type){枚举{...};之后,在 for 循环内使用 make_pair .};
  • 可以将数组和字符串指针与以下实用程序进行比较:
  • 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}
      

      用法: switch_(COMPARE(var)){{}} .

      这篇关于如何实现通用开关/大小写,该开关/大小写也可以在常规C ++类型上运行并且在语法上相似?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆