Chapter 14 Templates 0 2018, SEU. All rights reserved. 1
© 2009, SEU. All rights reserved. © 2018, SEU. All rights reserved. 1 Templates Chapter 14
OBJECTIVES o To use function templates to conveniently create a group of related (overloaded) functions o To distinguish between function templates and function-template specializations o To use class templates to create a group of related types. To distinguish between class templates and class-template specializations. o To overload function templates To understand the relationships among templates, friends, inheritance and static members 0 2018, SEU. All rights reserved. 2
© 2009, SEU. All rights reserved. © 2018, SEU. All rights reserved. 2 OBJECTIVES To use function templates to conveniently create a group of related (overloaded) functions. To distinguish between function templates and function-template specializations. To use class templates to create a group of related types. To distinguish between class templates and class-template specializations. To overload function templates. To understand the relationships among templates, friends, inheritance and static members
Topics o 14.1 Introduction o 14.2 Function Templates o 14.3 Overloading Function Templates o 14.4 Class Templates o 14.5 Nontype Parameters and Default Types for Class Templates o 14.6 Notes on Templates and Friends o 14.7 Notes on Templates and static Members 0 2018, SEU. All rights reserved. 3
© 2009, SEU. All rights reserved. © 2018, SEU. All rights reserved. 3 Topics 14.1 Introduction 14.2 Function Templates 14.3 Overloading Function Templates 14.4 Class Templates 14.5 Nontype Parameters and Default Types for Class Templates 14.6 Notes on Templates and Friends 14.7 Notes on Templates and static Members
14.1 Introduction o Motivation 实现支持不同数据类型的取最大值函数 (例:支持int、 double、 Hugelnt等) 实现支持不同数据类型的Aray类(例: 支持int、 double、 NugeNt等) 0 2018, SEU. All rights reserved. 4
© 2009, SEU. All rights reserved. © 2018, SEU. All rights reserved. 4 14.1 Introduction Motivation 实现支持不同数据类型的取最大值函数 (例:支持int、double、HugeInt等) 实现支持不同数据类型的Array类(例: 支持int、double、HugeInt等)
14.1 Introduction 模板( template):利用一种完全通用的方法来设 计函数或类而不必预先说明将被使用的每个对象 的类型,利用模板功能可以构造相关的函数或类 的系列,因此模板也可称为参数化的类型 泛型编程( Generic Programming °在C++语言中,模板可分为类模板( class template)和函数模板( (function template) 0 2018, SEU. All rights reserved. 5
© 2009, SEU. All rights reserved. © 2018, SEU. All rights reserved. 5 14.1 Introduction 模板(template): 利用一种完全通用的方法来设 计函数或类而不必预先说明将被使用的每个对象 的类型,利用模板功能可以构造相关的函数或类 的系列,因此模板也可称为参数化的类型。—— 泛型编程(Generic Programming) 在 C++ 语 言 中 , 模 板 可 分 为 类 模 板 (class template)和函数模板(function template)