如何常量映射变量

How to const map variables

本文关键字:映射 变量 常量 何常量      更新时间:2023-10-16

我有三个变量int a,b,c,我用它来选择第四个变量d的值。

一个简短的布尔示例:

a=0, b=0, c=0 -> d=0
a=0, b=0, c=1 -> d=1
a=0, b=1, c=0 -> d=2
a=0, b=1, c=1 -> d=1
and so on...

我想过创建一个 constexpr 矩阵来创建映射。缺点是它会生成不可读的代码。有没有更好的选择? 也许是一些提升库或已知的设计模式?

我正在用 c++11 编程

谢谢:)

如果可以提供abc作为模板参数,而不是函数参数,则可以定义一个具有三个bool参数的模板,然后为感兴趣的组合提供显式实现,如下所示:

template<bool A, bool B, bool C> constexpr int index() { return -1; }
// Truth table
template<> constexpr int index< true, false,  true>() { return 9; }
template<> constexpr int index< true, false, false>() { return 24; }
...

以下是调用这些函数的方法:

cout << index<true,false,true>() << endl; // Prints 9

演示。