C++程序员应了解的那些事:C++ 核心准则之 ~ Templates and generic programming

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

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值