面试题答案
一键面试设计思路
- 定义函数指针类型别名:为不同的计算操作定义函数指针类型,方便后续使用。
- 实现具体计算函数:编写加、减、乘、除等具体的计算函数。
- 创建模板元编程计算引擎:通过模板参数来选择对应的函数指针,并在编译期调用相应的函数进行计算。
代码实现细节
// 定义加函数
int add(int a, int b) {
return a + b;
}
// 定义减函数
int subtract(int a, int b) {
return a - b;
}
// 定义乘函数
int multiply(int a, int b) {
return a * b;
}
// 定义除函数
int divide(int a, int b) {
return a / b;
}
// 函数指针类型别名
using AddFuncPtr = int (*)(int, int);
using SubtractFuncPtr = int (*)(int, int);
using MultiplyFuncPtr = int (*)(int, int);
using DivideFuncPtr = int (*)(int, int);
// 模板元编程计算引擎
template <typename FuncPtr, int a, int b>
struct CompileTimeCalculator {
static const int result;
};
template <int a, int b>
struct CompileTimeCalculator<AddFuncPtr, a, b> {
static const int result = add(a, b);
};
template <int a, int b>
struct CompileTimeCalculator<SubtractFuncPtr, a, b> {
static const int result = subtract(a, b);
};
template <int a, int b>
struct CompileTimeCalculator<MultiplyFuncPtr, a, b> {
static const int result = multiply(a, b);
};
template <int a, int b>
struct CompileTimeCalculator<DivideFuncPtr, a, b> {
static const int result = divide(a, b);
};
int main() {
// 使用编译期计算引擎
static_assert(CompileTimeCalculator<AddFuncPtr, 3, 5>::result == 8, "Addition failed");
static_assert(CompileTimeCalculator<SubtractFuncPtr, 5, 3>::result == 2, "Subtraction failed");
static_assert(CompileTimeCalculator<MultiplyFuncPtr, 3, 5>::result == 15, "Multiplication failed");
static_assert(CompileTimeCalculator<DivideFuncPtr, 10, 2>::result == 5, "Division failed");
return 0;
}
在上述代码中:
- 首先定义了加、减、乘、除四个具体的计算函数。
- 然后为这四个函数定义了对应的函数指针类型别名。
CompileTimeCalculator
模板类根据传入的函数指针模板参数,在编译期选择合适的函数执行计算,并将结果作为静态常量result
提供。- 在
main
函数中,通过static_assert
来验证编译期计算的结果是否正确。