前言
C++的泛型编程是一种基于模板的编程技术,它允许在编写代码时使用未知的数据类型。泛型编程的目标是实现可重用、灵活和高效的代码。在C++中,泛型编程主要通过模板来实现。模板是一种用来生成代码的蓝图,它可以根据不同的数据类型生成特定的代码。
1.C++提供了两种模板:函数模板和类模板。除了C++提供的函数模板和类模板,还有介于这两者之间的类成员函数模板。
2.模板具体化(Template Specialization)是一种特殊情况,它允许为特定的模板参数提供特定的实现。当模板代码无法满足特定类型或特定条件的需求时,可以使用模板具体化来提供针对这些特定情况的定制实现。模板具体化分为两种类型:完全具体化(Full Specialization)和偏特化(Partial Specialization)。完全具体化:完全具体化是对模板的每个模板参数都提供了特定的实现。偏特化:偏特化是对模板的部分模板参数提供特定的实现。
函数模板
代码如下:
#include <iostream>
template <typename T>
T tempConver(T val);
int main(int argc, char *argv[])
{
const int intInput[] = {
12, 13};
const float floatInput[] = {
12.0, 12.4, 12.5, 13.0};
for (auto val : intInput) {
auto temp = tempConver(val);
std::cout << "[int]" << val << " -> " << temp << ": " << typeid(temp).name() << std::endl;
}
std::cout << std::endl;
for (auto val : floatInput) {
auto temp = tempConver(val);
std::cout << "[float]" << val << " -> " << temp << ": " << typeid(temp).name() << std::endl;
}
std::cout << std::endl;
return 0;
}
template <typename T>
T tempConver(T val)
{
auto tempF = ((val * (9 / 5)) + 32.00);
T ret = static_cast<T>(tempF);
return ret;
}
运行结果如下:
[int]12 -> 44: i
[int]13 -> 45: i
[float]12 -> 44: f
[float]12.4 -> 44.4: f
[float]12.5 -> 44.5: f
[float]13 -> 45: f
类模板
代码如下:
#include <iostream>
#include <memory>
template <typename T>
class UnitConver {
public:
T tempConve