我想将运行时值int v
转换为对带有非类型模板参数v
,例如template <int v> void hello()
的相应函数的调用。
这是编写它的蛮力方式:
using fn_type = void();
template <int v>
void hello() {
// of course ITRW this function requires v to be a
// constexpr value
printf("hello: %d\n",v);
}
static std::array<fn_type *,3> lut = {
hello<0>,hello<1>,hello<2>
};
void hello_dispatch(int v) {
lut[v](); // we don't handle OOB values b/c we are naughty like that
}
我可以将其用于3个值,但是对于更多的值,或者当限制本身是由其他编译时值计算得出的,这是不切实际的。
如何在编译时初始化LUT 2 而不在初始化程序中明确列出各种实例hello<0>,...
?
这是我想出的:
template <size_t I,size_t MAX>
constexpr void make_helper(std::array<fn_type *,MAX>& a) {
if constexpr (I < MAX) {
a[I] = hello<I>;
make_helper<I + 1,MAX>(a);
}
}
template <size_t MAX>
constexpr std::array<fn_type *,MAX> make_lut() {
std::array<fn_type *,MAX> ret{};
make_helper<0,MAX>(ret);
return ret;
}
static constexpr std::array<fn_type *,3> lut2 = make_lut<3>();
在C ++ 17中,必须有一些更简单,更好和更惯用的东西,尤其是不需要递归的东西。
2 或者,如果这是一个XY问题,如何在没有LUT(但至少具有LUT效率)的情况下实现hello_dispatch
。