我有许多函数q1, q2,q3等,每个函数都有不同的返回类型(int, int64_t,std::string等)。
我还有一个print_result函数可以打印出他们的结果(以及他们运行的时间,但为了简单起见在这里进行了修剪):
template <typename T>
void print_result(T (*func)()) {
T res = func();
std::cout << res << std::endl;
}
我也有很大的 switch 语句来打印每个函数的结果:
switch (question_num) {
case 1: print_result(q1); break;
case 2: print_result(q2); break;
case 3: print_result(q3); break;
// ...
}
目标:我想用模板函数替换这个 switch 语句,以避免每次添加新函数时复制每一行。
我曾尝试查看C++ 模板实例化:避免长开关,但我是模板元编程的新手,所以不确定如何准确处理。
我目前无法编译的尝试:
template <<int, typename> ...> struct FuncList {};
template <typename T>
bool handle_cases(int, T, FuncList<>) {
// default case
return false;
}
template <<int I, typename T> ...S>
bool handle_cases(int i, T (*func)(), FuncList<T, S...>) {
if (I != i) {
return handle_cases(i, func, FuncList<S...>());
}
print_result(func);
return true;
}
template <typename ...S>
bool handle_cases(int i, T (*func)()) {
return handle_cases(i, func, FuncList<S...>());
}
// ...
bool res = handle_cases<
<1, q1>, <2, q2>, <3, q3>
>(question_num);
// ...
我使用这个模板的理想方式显示在最后一行。
请注意,那里提供了从功能编号到功能的映射。函数编号是固定的,即q1映射到常量1并且在运行时不会改变。
编译错误(它可能相当基本,但我真的不太了解元编程):
error: expected unqualified-id before ‘<<’ token
17 | template <<int, typename> ...> struct FuncList {};
| ^~