编写泛型程式

今天在看到中文版C++ Primer 4/4的16.1.6这一小节时,有这样一段叙述:‘有些读者可能会认为大小比较动作如果以<和>运算子执行,会更自然些:

//预期的比较动作
if(v1 < v2) return -1;
if(v1 > v2) return 1;
return 0;

然而若写成这样:

//预期的比较动作
if(v1 < v2) return -1;
if(v1 > v2) return 1;
return 0;

就是减少“对引数型别的需求量”。在这儿,引数型别必须支援<但不必同时支援>。’

等一下,这两段程式码为何一模一样?作者到底要表达什么?我只好翻看英文版的说明:‘Some readers might think it would be more natural for the comparisons to be done using both the < and > operators:

     // expected comparison
     if (v1 < v2) return -1;
     if (v1 > v2) return 1;
     return 0;

However, by writing the code as

     // expected comparison
     if (v1 < v2) return -1;
     if (v2 < v1) return 1; // equivalent to v1 > v2
     return 0;

we reduce the requirements on types that can be used with our compare function. Those types must support <, but they need not also support >.’

看出错误来了,原来是v2 < v1喔,哈哈!发现书中有bug,超有成就感的!