C++ 函数模板示例 2 (配合decltype)

本文探讨了C++中的函数模板及其配合decltype的使用,通过具体示例展示了如何在实际编程中灵活应用,以提高代码的泛用性和效率。详细内容可参考《Visual C++ 2012入门经典》一书中第212页的6.8节。
摘要由CSDN通过智能技术生成
#include "stdafx.h"
#include <iostream>
#include <iomanip>
#include <string.h>
#include <new>

using std::cout;
using std::cin;
using std::endl;
using std::setw;

template<class T1, class T2> 
auto product(T1 v1[], T2 v2[], size_t count) -> decltype(v1[0]*v2[0])
{
	decltype(v1[0]*v2[0]) sum(0);
	for(size_t i=0;i<count;i++) sum += v1[i]*v2[i];
	return sum;
}


int main(int argc,_TCHAR* argv[])
{
	double x[] = {100.5,99.5,88.7,77.8};
	short y[] = {3,4,5,6};
	long z[] = {11L,22L,33L,44L};

	size_t n=4;

	cout <<"result type is " <<typeid(product(x,y,n)).name()<<endl;
	cout<<"result is "<<product(x,y,n)<<endl;


	cout <<"result type is " <<typeid(product(z,y,n)).name()<<endl;
	cout<<"result is "<<product(z,y,n)<<endl;


	return 0;
}

                
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值