面试题答案
一键面试关键设计思路
- 抽象基类与虚函数:
- 定义一个抽象基类,例如
AlgorithmBase
,其中包含一个虚函数execute
,用于执行具体的算法操作。不同的算法策略类继承自这个基类,并实现execute
函数。这是利用C++多态性的基础。
- 定义一个抽象基类,例如
- 模板元编程:
- 使用模板类来处理不同的数值类型。将数值类型作为模板参数传递给模板类,模板类可以包含针对该数值类型优化的代码。
- 通过模板特化,可以为不同的数值类型提供特定的实现,从而达到高效执行的目的。
- 组合使用:
- 在模板类中,可以包含指向
AlgorithmBase
类型的指针(或智能指针),这样在运行时可以根据具体需求选择不同的算法策略。同时,模板类根据数值类型参数进行编译期优化。
- 在模板类中,可以包含指向
核心代码示例
// 抽象算法基类
class AlgorithmBase {
public:
virtual void execute() = 0;
virtual ~AlgorithmBase() = default;
};
// 具体算法策略类,例如快速傅里叶变换的一种实现
class FFTAlgorithm : public AlgorithmBase {
public:
void execute() override {
// 具体的FFT实现代码
std::cout << "Executing FFT algorithm" << std::endl;
}
};
// 模板类,处理不同数值类型
template <typename T>
class NumericalComputation {
private:
std::unique_ptr<AlgorithmBase> algo;
public:
NumericalComputation(std::unique_ptr<AlgorithmBase> a) : algo(std::move(a)) {}
void performComputation() {
// 针对数值类型T的特定操作
std::cout << "Performing computation for type " << typeid(T).name() << std::endl;
algo->execute();
}
};
// 模板特化示例,为double类型提供更优化的实现
template <>
class NumericalComputation<double> {
private:
std::unique_ptr<AlgorithmBase> algo;
public:
NumericalComputation(std::unique_ptr<AlgorithmBase> a) : algo(std::move(a)) {}
void performComputation() {
// 针对double类型的更优化操作
std::cout << "Performing optimized computation for double" << std::endl;
algo->execute();
}
};
使用示例:
int main() {
auto fftAlgo = std::make_unique<FFTAlgorithm>();
NumericalComputation<float> compFloat(std::move(fftAlgo));
compFloat.performComputation();
auto newFFTAlgo = std::make_unique<FFTAlgorithm>();
NumericalComputation<double> compDouble(std::move(newFFTAlgo));
compDouble.performComputation();
return 0;
}
在上述代码中,AlgorithmBase
及其派生类实现了多态性,不同的算法策略可以通过继承 AlgorithmBase
并实现 execute
函数来添加。NumericalComputation
模板类通过模板参数处理不同数值类型,并且可以在运行时选择不同的算法策略,实现了高度可扩展的架构。模板特化 NumericalComputation<double>
展示了如何为特定数值类型提供更优化的实现。