例子:计算vector的点乘 , 计算过程为 a[0]*b[0] + a[1]*b[1] + a[2]*b[2]
#include <iostream>
template <typename T>
inline T dot_product(int dim, T* a, T* b){
T result = T();
for(int i = 0; i < dim; i++){
result += a[i] * b[i];
}
return result;
}
int main(){
int a[3] = {1, 2, 3};
int b[3] = {5, 6, 7};
printf("%d", dot_product(3, a, b));
}
但是上面的实现太耗时间。一把来讲,直接将循环展开为a[0]*b[0] + a[1]*b[1] + a[2]*b[2]性能更好。我们可以这样写:
#include <iostream>
// 基本模板
template <int DIM, typename T>
class DotProduct{
public:
static T result(T *a, T*b){
return *a * *b + DotProduct<DIM - 1, T> ::result(a + 1, b + 1);
}
};
//作为结束条件的局部特化
template <typename T>
class DotProduct<1, T>{
public:
static T result(T *a, T * b){
return *a * *b;
}
};
// 辅助函数
template <int DIM, typename T>
inline T dot_product(T* a, T* b){
return DotProduct<DIM, T>::result(a, b);
}
int main(){
int a[3] = {1, 2, 3};
int b[3] = {5, 6, 7};
printf("%d", dot_product<3>(a, b));
}