- // 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 error,compile or runtime,encountered.As the excise goes,if the call of compare("hi","world") is invoked,there is an compile error labeled as C2782 whose context is as follow:
- Error 14 error C2782: 'int Compare(const T &,const T &)' : template parameter 'T' is ambiguous g:/vsproject/cprimer/cprimer/main.cpp 39
There is no error,compile or runtime,encountered.As the excise goes,if the call of compare("hi","world") is invoked,there is an compile error labeled as C2782 whose context is as follow:
Error 14 error C2782: 'int Compare(const T &,const T &)' : template parameter 'T' is ambiguous g:/vsproject/cprimer/cprimer/main.cpp 39
if "world" is sliced down to the same size as "hi" is, the program runs well,but the output maybe randomly 1, -1,or 0 since the comparison applied is not to the literal value of char *, but the address of the literal value, instead.
如果字符串长度相同时,函数的默认比较是两个字符串的地址的话,那么其长度不同时的调用会ambiguous?,此问题有待解决。
Appendix:
如果执行compare((int)"hi",(int)"world") 的话,比较的将是其地址的大小,
而compare(string("hi"),string("world"))的话,比较的是字符串"hi" and "world"的按位ASCII码的大小!