枚举中下一项的编译时计算

Compile time calculation of next item in enum?

本文关键字:一项 编译 计算 枚举      更新时间:2023-10-16

例如,我有一个enum

enum Option
{
   A = 0, B = 1, C = 2
};

,我想得到它的编译时间下一个结果,即nextOf<A> = B, nextOf<B> = C, nextOf<C> = A,我如何实现它?

您可以使用constexpr来编写编译时函数。

#include <iostream>
enum Option
{
   A = 0, B = 1, C = 2
};
constexpr Option nextOf(const Option option){
  switch (option){
    case A: return B;
    case B: return C;
  }
  return A;
}
int main (){
  constexpr Option next = nextOf(A);
}

另一种方法是使用结构的部分专门化。
例如:

enum Option { A = 0, B = 1, C = 2 };
template<Option>
struct next;
template<> struct next<A> { static constexpr Option value = B; };
template<> struct next<B> { static constexpr Option value = C; };
template<> struct next<C> { static constexpr Option value = A; };
template<Option O>
constexpr Option next_v = next<O>::value;
int main (){
    constexpr Option next = next_v<A>;
    static_assert(next_v<B> == C, "!");
}

由于enum s是伪装的整数,您可以简单地定义

contexpr Option next(Option u)
{
   return (Option(int(u)+1);
}

当然这让next(C)作为未定义行为。另一种选择可以是%3的结果,这样next(C) = a (int-s上典型的绕行算术)

   return (Option((int(u)+1)%3);

或输入上的过滤器,抛出异常,但这将使函数不再consterxpr