C++Primer读书笔记(十一)

来源:互联网 发布:三菱伺服驱动器编程 编辑:程序博客网 时间:2024/05/17 02:20

函数匹配与函数模板

如果重载函数中既有普通函数又有函数模板,确定函数调用步骤如下:

1、为这个函数名建立候选函数集合,包括:
a、与被调用函数名字相同的任意普通函数
b、任意函数模板实例化,在其中,模板实参推断发现了与调用中所用函数实参想匹配的模板实参
2、确定哪些普通函数是可行的。候选集合中的每个模板实例都是可行的,因为模板实参推断保证函数可以被调用
3、如果需要转换来进行调用,根据转换的种类排列可行函数,记住,调用模板函数的实例所允许的转换是有限的
a、如果只有一个函数可选,就调用这个函数
b、如果调用有二义性,从可行函数集合中去掉所有函数模板实例
4、重新排列去掉的函数模板实例的可行函数
a、如果只有一个函数可选,就调用这个函数
否则,调用有二义性。
举例:
template <typename T> int Compare(const T &v1, const T &v2)
{
if(v1 > v2) return 1;
    if(v1 < v2) return -1;
return 0;
}
template<class U, class V> int Compare(U, U, V)
{
return 0;
}
int Compare(const char *v1, const char *v2)
{
if(v1 > v2) return 1;
if(v1 < v2) return -1;
return 0;
}


int main(int argc, char* argv[])
{
//call compare(const T&, const T&) with T bound to int
Compare(1, 0);
//call Compare(U, U, V) with U&V bound to vector<int>::iterator
vector<int> ivec1(10), ivec2(20);
Compare(ivec1.begin(), ivec1.end(), ivec2.begin());
int ival[] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
   //call Compare(U, U, V) with U bound to int*
// V bound with vector<int>::iterator
Compare(ival, ival + 10, ivec1.begin());
//calls the ordinary function taking const char* parameters
const char const_arr1[] = "TQ", const_arr2[] = "JC";
Compare(const_arr1, const_arr2);
return 0;
}
原创粉丝点击