我碰巧读了一篇关于它的文章,所以我复制给你。可能是在书中介绍的:C++ 模板:完整指南。
#include <iostream>
template<int DIM,typename T>
struct DotProduct {
static T execute(const T v1[],const T v2[]);
};
template<int DIM,typename T>
T DotProduct<DIM,T>::execute(const T v1[],const T v2[]) {
return v1[0]*v2[0] + DotProduct<DIM-1,T>::execute(v1+1,v2+1);
};
template<typename T>
struct DotProduct<1,T> {
static T execute(const T v1[],const T v2[]);
};
template<typename T>
T DotProduct<1,T>::execute(const T v1[],const T v2[]) {
return v1[0]*v2[0];
};
int main()
{
int v1[] = {1,2,3};
int v2[] = {4,5,6};
int r2 = DotProduct<3,int>::execute(v1,v2);
std::cout << r2 << std::endl;
return 0;
}