C++核心准则T.1:使用模板提高代码的抽象水平
T.1: Use templates to raise the level of abstraction of code
T.1:使用模板提高代码的抽象水平
Reason(原因)
Generality. Reuse. Efficiency. Encourages consistent definition of user types.
普遍性。重用。效率。鼓励用户类型的一致性。
Example, bad(反面示例)
Conceptually, the following requirements are wrong because what we want of T is more than just the very low-level concepts of "can be incremented" or "can be added":
概念上,我们希望T不仅限于可以进行增量操作或者可以作为被加数这样非常低水平的概念,因此下面的需求是错误的。
template<typename T>
// requires Incrementable<T>
T sum1(vector<T>& v, T s)
{
for (auto x : v) s += x;
return s;
}
template<typename T>
// requires Simple_number<T>
T sum2(vector<T>& v, T s)
{
for (auto x : v) s = s + x;
return s;
}
//原链接
https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#S-templates