C/C++编程:模板元编程中的循环

1059 篇文章 286 订阅

例子:计算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));
}

在这里插入图片描述

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值