最简单的C++模板样例


  1. // MaxTemplate.cpp : Defines the entry point for the console application.
  2. //
  3. #include "stdafx.h"
  4. #include <iostream>
  5. #include <string>
  6. using namespace std;
  7. template <typename T>
  8. inline T const& max(T const& a, T const& b)
  9. {
  10.     return a > b ? a : b; 
  11. }
  12. //test
  13. int main()
  14. {
  15.     int a = 0;
  16.     int b = 0;
  17.     
  18.     //给a b 赋值为随机数
  19.     a = ::rand();
  20.     b = ::rand();
  21.     cout << "max(" << a << ", " << b << ") = " << ::max(a, b) << endl;
  22.     double du1 = 0.0;
  23.     double du2 = 0.0;
  24.     du1 = (double)rand() / 10000;
  25.     du2 = (double)rand() / 10000;
  26.     cout << "max(" << du1 << ", " << du2 << ") = " << ::max(du1, du2) << endl;
  27.     string str1 = "hello";
  28.     string str2 = "test";
  29.     cout << "max(" << str1 << ", " << str2 << ") = " << ::max(str1, str2) << endl;
  30.     return 0;
  31. }


程序调用了 max()三次。第一次所给自变量是两个 int,第二次所给自变量是两个 double,最后一 次
给的是两个 std::string。每一次 max()均比较两值取其大者。程序运行结果为:
max(7,i): 42
max(f1,f2): 3.4
max(s1,s2): mathematics
注意程序对max()的三次调用都加了前缀字 "::",以便确保被调用的是我们在全局命名空间
(global namespace)中定义的 max()。标准库内也有一个 std::max() template,可能会在某些情
况下被调用,或在调用时引发模棱两可(ambiguity,歧义性)。
一般而言,templates 不会被编译为「能够处理任意类型」的单一实体(entity),而是被编译为
多个个别实体,每一个处理某一特定类型。因此,针对三个类型,max()被编译成三个实体。 例
如第一次调用 max():
int i = 42;
    max(7,i)    
使用的是「以int 为 template parameter T」的 function template,语意上等同于调用以下函数:
inline int const& max (int const& a, int const& b)
{
// 如果 a<b 就传回 b,否则传回 a
return a < b ? b : a;
}
以具体类型替换 template parameters 的过程称为「实例化」(instantiation,或称「实体化」)。
过程中会产生 template 的一份实体(instance)。不巧的是,instantiation(实例化、实例化产品)
和instance(实体)这两个术语在OO(面向对象)编程领域中有其它含义,通常用来表示一个 class
的具体对象(concrete object)。本书专门讨论 templates,因此当我们运用这个术语时,除非另
有明确指示,表达的是 templates 方面的含义。
注意,只要 function template 被使用,就会自动引发实例化过程。程序员没有必要个别申请实例化
过程。
类似情况,另两次对 max()的调用被实例化为:
const double& max (double const&, double const&);
const std::string& max (std::string const&, std::string const&);
如果试图以某个类型来实例化 function template,而该类型并未支持 function template 中用到的操
作,就会导致编译错误。例如:
std::complex<float> c1, c2; // 此类型并不提供 operator<
   
max(c1,c2); // 编译期出错
实际上,templates 会被编译两次:
1. 不实例化,只是对 template 程序代码进行语法检查以发现诸如「缺少分号」等等的语法错误。
2. 实例化时,编译器检查 template 程序代码中的所有调用是否合法,诸如「未获支持之函数调用」

便会在这个阶段被检查出来。
这会导致一个严重问题:当 function template 被运用而引发实例化过程时,某些时候编译器需要
用到template 的原始定义。一般情况下,对普通的(non-template)functions而言,编译和链接两
步骤是各自独立的,编译器只检查各个functions的声明语句是否和调用语句相符,然而template 的
编译破坏了这个规则。解决办法在第6章讨论。眼下我们可以用最简单的解法:把template 程序代
码以 inline 形式写在头文件(header)中。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值