枚举中下一项的编译时计算
Compile time calculation of next item in enum?
例如,我有一个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
。
相关文章:
- Qt Visual Studio 2015 加载项编译问题
- std::ifstream 在读取文件中最后一项时设置 eofbit,但仅在读取数值类型时发生
- 访问类成员向量最后一项的正确方法
- 我正在尝试解决英特尔架构并行基础课程中关于 Coursera 的一项作业
- 从函数参数包中删除最后一项
- 以不同的方式替换每一项,regex c++
- 根据计算机上安装的库依赖项编译不同的代码
- 使用 fstream 在空格分隔文件中查看下一项(不仅仅是一个字符)的方法
- 在 QSet 中插入元素<QString>并检索 ,删除 QSet 的最后一项
- ClCompile项目也是一项任务
- 等待所有线程完成一项工作,然后执行另一项工作
- 链接列表中最后一项之后的项目是否为0
- C++ 迭代一项 - UB 或定义的行为
- 如何在Linux / Windows操作系统上使用文件*.cpp一步编译下面的代码
- 无法通过一次编译所有文件来解决的链接器错误
- EXIT_SUCCESS和EXIT_FAILURE.它是在任何地方运行一次编译,还是在任何地方编写一次编译
- 如何在Linux中使用Makefile一次编译一堆测试C++文件
- 如何一次编译多个独立的CPP文件
- C++:映射,键的上一项
- 枚举中下一项的编译时计算