void may(int); // #1
float may(float, float = 3); // #2
void may(char); // #3
char * may(const char *); // #4
char may(const char &); // #5
template<class T> void may(const T &); // #6
template<class T> void may(T *); // #7
1. 完全匹配,但常规函数优先于模板。
2. 提升转换 (例如,char 和 shorts 自动转换为 int,float 自动转换为 double)。
3. 标准转换 (例如,int 转换为 char,long 转换为 double)。
4. 用户定义的转换,如类声明中定义的转换。
从实参 | 到形参 |
Type | Type & |
Type & | Type |
Type [] | Type * |
Type (argument-list) | Type (*) (argument-list) |
Type | const Type |
Type | volatile Type |
Type * | const Type * |
Type * | volatile Type * |
void recycle(blot); // #1 blot-to-blot
void recycle(const blot); // #2 blot-to-(const blot)
void recycle(blot &); // #3 blot-to-(blot &)
void recycle(const blot &); // #4 blot-to-(const blot &)
#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];
// 指向结构中的 amount
for (int i = 0; i < 3; i++)
pd = &mr_E.amount;
cout << "Listing Mr. E's counts of things:\n";
ShowArray(things, 6); // 使用模板A
cout << "Listing Mr. E's debts:\n";
ShowArray(pd, 3); // 使用模板 B
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 << ' ';
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 << ' ';
cout << endl;
}
重载解析将寻找最匹配的函数。如果只存在一个这样的函数,则选择它。如果存在多个这样的函数,但其中只有一个是非模板函数,则选择该函数。如果存在多个适合的函数,且它们都为模板函数,但其中有一个函数比其他函数更具体,则选择该函数。如果有多个同样合适的非模板函数或模板函数,但没有一个函数比其他函数更具体,则函数调用是不确定的,因此是错误的。当然,如果不存在匹配的函数,那么也是错误的。
// choices.cpp -- choosing a template
#include <iostream>
template<class T>
T lesser(T a, T b) // #1
{
return a < b ? a : b;
}
int lesser(int a, int b) // #2
{
a = a < 0 ? -a : a;
b = b < 0 ? -b : b;
return a < b ? a : b;
}
int main()
{
using namespace std;
int m = 20;
int n = -30;
double x = 15.5;
double y = 25.9;
cout << lesser(m, n) << endl; // use #2
cout << lesser(x, y) << endl; // use #1 with double
cout << lesser<>(m, n) << endl; // use #1 with int
cout << lesser<int>(x, y) << endl; // use #1 with int
// cin.get();
return 0;
}
20
15.5
-30
15
欢迎光临 曲径通幽论坛 (http://www.groad.net/bbs/) | Powered by Discuz! X3.2 |