我是靠谱客的博主 落寞冷风,这篇文章主要介绍函数重载、函数模板、显式具体化,现在分享给大家,希望可以做个参考。

函数重载

同一函数名接受不同参数来区分

复制代码
1
2
3
4
5
6
void print(const char * str, int width); void print(double d, int width); void print(long l, int width); void print(int i, int width); void print(const char * str);
  1. 根据参数(数量、类型、排列顺序)来区分

  2. 不区分double cube(double x)double cube(double &x),因为调用时都是cube(x)

  3. 匹配函数时不区分const和非const变量

    复制代码
    1
    2
    3
    4
    5
    void d(char * bits); //使用该函数时只接受const参数 void d(const char * bits); //使用该函数时接收const参数和非const参数
  4. 只能改变参数,不能改变函数类型

    复制代码
    1
    2
    3
    4
    int a(int a); double a(double a); //不能重载:函数类型不相同
  5. 仅在函数内容基本相同,但需要接收不同类型的参数时使用函数重载

函数模板

用泛型来传参

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
template <typename AnyType> //建立一个模板,将类型命名为AnyType //template <class AnyType> 相同 void swap(AnyType &a, AnyType &b) { AnyType temp; temp = a; a = b; b = temp; }

重载的模板

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
template <typename T> void Swap(T &a, T &b) { T temp; temp = a; a = b; b = temp; } template <typename T> void Swap(T a[], T b[] ,int n) { T temp; for(int i=0;i<n;i++) { temp = a[i]; a[i] = b[i]; b[i] = temp; } }

显式具体化

使模板能够对结构成员进行操作

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
struct job { char name[40]; double salary; }; template <typename T> void Swap(T &a, T &b) { T temp; temp = a; a = b; b = tmep; } template <> void Swap<job>(job &j1, job &j2) { double t1; t1 = j1.salary; j1.salary = j2.salary; j2.salary = t1; } int main() { job a = {"Sue",100.5}; job b = {"Joe",120.23}; Swap(a,b); //参数是结构,调用显式具体化函数 Swap(a.salary,b.salary); //参数是结构成员,调用原函数 cout << "a:" << a.salary << "tb:" << b.salary << endl; Swap(a.salary,b.salary); cout << "a:" << a.salary << "tb:" << b.salary << endl; }
复制代码
1
2
3
4
a:120.23 b:100.5 a:100.5 b:120.23

显式实例化

直接命令编译器创建特定的实例

复制代码
1
2
template void Swap<int>(int, int);

区分实例化template <> void Swap<job>(job &j1, job &j2)与具体化template void Swap<int>(int, int);

完全匹配

从实参到形参
TypeType &
Type &Type
Type []* Type
Type(argument-list)Type (*)(argument=list)
Typeconst Type
Typevolatile Type
Type *const Type
Type *volatile Type *
  • 指向非const数据的指针和引用优先与非const指针和引用参数匹配

  • 非模板函数优先于模板函数(包括显示具体化)

    | const Type |
    | Type * | volatile Type * |

  • 指向非const数据的指针和引用优先与非const指针和引用参数匹配

  • 非模板函数优先于模板函数(包括显示具体化)

最后

以上就是落寞冷风最近收集整理的关于函数重载、函数模板、显式具体化的全部内容,更多相关函数重载、函数模板、显式具体化内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(62)

评论列表共有 0 条评论

立即
投稿
返回
顶部