如何在C ++中为具有类似语法的非整数类型实现常规的switch / case?

问题描述 投票:2回答:2

在C / C ++中,switch/case将积分与编译时间常数进行比较。无法使用它们来比较用户/库定义的类型,例如std::stringWhy the switch statement cannot be applied on strings?

我们可以实现look-a-like switch/case,它给出相似的语法糖,并且可以避免简单的if/else比较。


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

简而言之,如果为类型switch/case定义了operator==,则应该可以运行此X。即:]]

X x1{"Hello"}, x2{"World"};
switch(x2)
{
  // 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: Fun with switch statements中演示了一种方法。

在C / C ++中,switch / case将一个积分与编译时间常数进行比较。无法使用它们来比较用户/库定义的类型,例如std :: string。为什么switch语句不能是...

c++ switch-statement comparison c++17 syntactic-sugar
2个回答
1
投票

插图:
#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) static_assert(not std::is_pointer<decltype(X)>::value, "Pointer comparison!"); \
                   for(enum { INVALID, CASES, DEFAULT, BREAK, COMPARED } IS_ = CASES; \
                       IS_ != BREAK; assert(IS_ == BREAK or IS_ == DEFAULT)) \
                     for(const auto& VAR_ = X; IS_ != BREAK; IS_ == DEFAULT or (IS_ = BREAK)) \

#define case_(...) VA_MACRO(case_, __VA_ARGS__)
#define case_1(X)    } if(IS_ == COMPARED or  \
                          ((VAR_ == X) and (IS_ = COMPARED))) { CONCATE(case,__LINE__)
#define case_2(X,OP) } if(IS_ == COMPARED or  \
                            ((VAR_ OP X) and (IS_ = COMPARED))) { CONCATE(case,__LINE__)

#define default_ } if(IS_ == COMPARED or (IS_ == DEFAULT and (IS_ = COMPARED)) or \
                      not(IS_ = DEFAULT)) { CONCATE(default,__LINE__)

#define break_ } if(IS_ == COMPARED and (IS_ = BREAK)) break; { (void)0


0
投票

您无法避免以下情况:开关盒必须为constexpr整数,因此case x2:将不起作用。它必须是constexpr

模拟在constexpr字符串上切换的一种方法可能是使用constexpr哈希函数。


-2
投票

插图:

© www.soinside.com 2019 - 2024. All rights reserved.