您可以在内部使用模板来生成必要的代码。
一种方法是生成一个包含 100 个函数指针的调度表,然后在运行时对其进行索引。c_foo
将生成索引的编译时序列并调用助手:
extern "C" void c_foo(int i) {
c_foo_impl(std::make_integer_sequence<int,100>{}, i);
}
该助手将生成调度表并执行调用:
template <int... Is>
void c_foo_impl (std::integer_sequence<int,Is...>, int i) {
constexpr std::array<void(*)(), sizeof...(Is)> dispatch = { &foo<Is>... };
//assert or some other error handling for i > sizeof...(Is)
dispatch[i]();
}
然后你可以做同样的事情zoo
:
extern "C" void c_zoo(int i, int v) {
c_zoo_impl(std::make_integer_sequence<int,100>{}, i, v);
}
template <int... Is>
void c_zoo_impl (std::integer_sequence<int,Is...>, int i, int v) {
constexpr std::array<void(*)(int), sizeof...(Is)> dispatch = { &zoo<Is>... };
//assert or some other error handling for i > sizeof...(Is)
dispatch[i](v);
}
如果您发现在某些地方需要它,您可以抽象出一些细节,或者使用诸如Petra https://github.com/jacquelinekay/petra,它提供了一个switch_table
来进行这种映射。
现场演示 http://coliru.stacked-crooked.com/a/a30814607651e96e