- // implement strcmp-like generic compare function
- // returns 0 if the values are equal, 1 if v1 is larger, -1 if v1 is smaller
- template <typename T>
- int compare(const T &v1, const T &v2)
- {
- if (v1 < v2) return -1;
- if (v2 < v1) return 1;
- return 0;
- }
- Given the calls
- int main ()
- {
- // T is int;
- // compiler instantiates int compare(const int&, const int&)
- cout << compare(1, 0) << endl;
- // T is string;
- // compiler instantiates int compare(const string&, const string&)
- string s1 = "hi", s2 = "world";
- cout << compare(s1, s2) << endl;
- return 0;
- }
- There is no problem encountered,but if you invoke the call
- compare ("hi", "world");there is an error as below:
- Error 14 error C2782: 'int Compare(const T &,const T &)' : template parameter 'T' is ambiguous g:/vsproject/cprimer/cprimer/main.cpp 41
C++ Primer的习题16.3中,有这么一个问题:
compare ("hi", "world");其编译错误如上!
如果把"world" 砍到和"hi"同一个长度的话,比较将可以,不会出错。
(结果的正确性不可保证,因为默认比较的是两个char *的地址大小)
很奇怪,既然默认的是比较char*的地址,为什么长度不一致时却无法比较呢?,难道默认比较的是地址的推断有误?