C++中怎么使用部分排序规则
我们先看一个完整的程序,它使用部分排序规则来确定要使用哪个模板定义。程序清单 8.14有两个用来显示数组内容的模板定义。第一个定义(模板A)假设作为参数传递的数组中包含了要显示的数据;第二个定义(模板 B)假设数组元素为指针,指向要显示的数据。
// tempover.cpp --- template overloading
#include <iostream>
template <typename T> // template A
void ShowArray(T arr[], int n);
template <typename T> // template B
void ShowArray(T * arr[], int n);
struct debts
{
char name[50];
double amount;
};
int main()
{
using namespace std;
int things[6] = {13, 31, 103, 301, 310, 130};
struct debts mr_E[3] =
{
{"Ima Wolfe", 2400.0},
{"Ura Foxe", 1300.0},
{"Iby Stout", 1800.0}
};
double * pd[3];
// set pointers to the amount members of the structures in mr_E
for (int i = 0; i < 3; i++)
pd[i] = &mr_E[i].amount;
cout << "Listing Mr. E's counts of things:\n";
// things is an array of int
ShowArray(things, 6); // uses template A
cout << "Listing Mr. E's debts:\n";
// pd is an array of pointers to double
ShowArray(pd, 3); // uses template B (more specialized)
// cin.get();
return 0;
}
template <typename T>
void ShowArray(T arr[], int n)
{
using namespace std;
cout << "template A\n";
for (int i = 0; i < n; i++)
cout << arr[i] << ' ';
cout << endl;
}
template <typename T>
void ShowArray(T * arr[], int n)
{
using namespace std;
cout << "template B\n";
for (int i = 0; i < n; i++)
cout << *arr[i] << ' ';
cout << endl;
}
请看下面的函数调用:
ShowArray(things,6);
标识符 things 是一个 int 数组的名称,因此与下面的模板匹配:
template <typename T> // template A
void ShowArray(T arr[],int n);
其中 T 被替换为 int 类型。参见【0voice C++】
接下来,请看下面的函数调用:
ShowArray(pd,3);
其中 pd是一个 double * 数组的名称。这与模板 A 匹配:
template <typename T> //template A
void ShowArray(T arr[], int n);
其中,T被替换为类型 double*。在这种情况下,模板函数将显示pd数组的内容,即3个地址。该函数调用也与模板 B匹配:
template <typename T> //template B
void ShowArray(T *arr[],int n);
在这里,T 被替换为类型 double,而函数将显示被解除引用的元素 * arr[i],即数组内容指向的 double在这两个模板中,模板B更具体,因为它做了特定的假设–数组内容是指针,因此被使用。值。下面是程序清单 8.14中程序的输出:
Listing Mr.E's counts of things:
template A
13 31 103 301 310 130
Listing Mr.E's debts:
template B
2400 13001800
如果将模板B从程序中删除,则编译器将使用模板A来显示pd的内容,因此显示的将是地址,而不是值。请试试看。
简而言之,重载解析将寻找最匹配的函数。如果只存在一个这样的函数,则选择它;如果存在多个这样的函数,但其中只有一个是非模板函数,则选择该函数;如果存在多个适合的函数,且它们都为模板函数,但其中有一个函数比其他函数更具体,则选择该函数。如果有多个同样合适的非模板函数或模板函数,但没有一个函数比其他函数更具体,则函数调用将是不确定的,因此是错误的:当然,如果不存在匹配的函数,则也是错误。