C++ Primer Fourth Edition 16.7 的疑问!
不知道是不是错误,请高手帮忙看看
红色的部分说:
模板函数和普通函数都匹配,但事实上,当我把这个函数
int compare(const char*, const char*);
no matching function for call to 'compare(const char [6], const char [3])'
no matching function for call to 'compare(char [6], char [3])'
// compares two objects
template <typename T> int compare(const T&, const T&);
// compares elements in two sequences
template <class U, class V> int compare(U, U, V);
// plain functions to handle C-style character strings
int compare(const char*, const char*);
// calls compare(const T&, const T&) with T bound to int
compare(1, 0);
// calls compare(U, U, V), with U and V bound to vector<int>::iterator
vector<int> ivec1(10), ivec2(20);
compare(ivec1.begin(), ivec1.end(), ivec2.begin());
int ia1[] = {0,1,2,3,4,5,6,7,8,9};
// calls compare(U, U, V) with U bound to int*
// and V bound to vector<int>::iterator
compare(ia1, ia1 + 10, ivec1.begin());
// calls the ordinary function taking const char* parameters
const char const_arr1[] = "world", const_arr2[] = "hi";
compare(const_arr1, const_arr2);
// calls the ordinary function taking const char* parameters
char ch_arr1[] = "world", ch_arr2[] = "hi";
compare(ch_arr1, ch_arr2);
compare(ivec1.begin(), ivec1.end(), ivec2.begin())
compare(ia1, ia1 + 10, ivec1.begin()): In these calls, the only viable function is the instantiation of the template that has three parameters. Neither the template with two arguments nor the ordinary nonoverloaded function can match these calls.
compare(const_arr1, const_arr2): This call, as expected, calls the ordinary function. Both that function and the first template with T bound to const char* are viable. Both are also exact matches. By rule 3b, we know that the ordinary function is preferred. We eliminate the instance of the template from consideration, leaving just the ordinary function as viable.
compare(ch_arr1, ch_arr2): This call also is bound to the ordinary function. The candidates are the version of the function template with T bound to char* and the ordinary function that takes const char* arguments. Both functions require a trivial conversion to convert the arrays, ch_arr1 and ch_arr2, to pointers. Because both functions are equal matches, the plain function is preferred to the template version.
C++?Primer c++
[解决办法]
好多英文..
这是函数模版的重载?
[解决办法]
看了这么多分就进来了……
[解决办法]
首先肯定不会匹配3个参数的compare
然后你传递是const_arr1,那么模板推导出来的参数类型就是数组的引用
参数分别是 const char &[6] , const char &[3]这是2个不同的类型
int compare(const T&, const T&);要求两个参数都一致,所以无法匹配了。
compare((const char*)const_arr1, (const char*)const_arr2);
template <typename T, typename U> int compare(const T&, const U&);