C++ 函数模板示例 2 (配合decltype)
2015-06-08 18:44
477 查看
#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; }
</pre><pre name="code" class="cpp">上面代码的运行结果是:
更多完整的示例,可以参见《Visual C++ 2012入门经典》一书的212页,6.8节:使用函数的示例。
相关文章推荐
- c++解决 {ctor}构造函数不能有返回类型或者无故缺少“;”(在“using”的前面)的问题
- 虚析构函数
- 使用VC++压缩解压缩文件夹
- Zip Utils - clean, elegant, simple, C++/Win32
- C++中如何在一个构造函数中调用另一个构造函数
- C++中的Lambda表达式详解
- C++在Ubuntu上编译mysql问题
- C++——拼接+=
- C++ 调用webservice 出现 函数返回值为 3 (SOAP_TAG_MISMATCH) 的解决方案
- 多线程编程 c++ /thread(detach,join)/ _beginthreadex
- C++——字符串的拼接
- c++ pair类型
- 【Multiply Strings】cpp
- C++64位整型相乘取模的溢出处理(二)
- VS2010 C++ 操作Excel表格的编程实现
- 【C++】 VS2010 打开VS2012 新建的工程
- Effective C++学习笔记
- Effective C++学习笔记 分类: C/C++ 2015-06-08 16:52 27人阅读 评论(0) 收藏
- 线程池原理及创建(C++实现)
- vc++ 的指针和数组结合理解的最佳例子