Templates vs Interfaces

219 篇文章 ¥19.90 ¥99.00
25 篇文章
本文探讨了C++中模板类与接口的区别。通过创建CMyClass并将其包装到泛型类A<T>, B<T>, C<T>中,以及实现接口IA, IB, IC并让CMyClass继承这些接口,分析了两种方式在代码复用、优化和设计上的不同选择。同时讨论了模板特化和直接继承接口对于特定实现的影响。" 128206041,11528125,2022年Q3智能手机品牌销售额同比增长:vivo领先,"['数据可视化', '数据分析', '智能手机市场']

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

It seems another religion war has started between template fans ("Wrap, Wrap, Wrap") and virtual functions fans ("Derive, Derive, Derive").

If I want and obje that is A-able, B-able and C-Able I can:

  1. Create CMyClass and then wap it into A<T>, B<T>, C<T> (and eventually specialize some of them)
  2. Create interface IA, IB and IC, implement as CAimpl, CBimpl and CCimpl and then derive CMyclass from CAimpl, CBimpl, CCimpl (or directly fom IA, IB and IC if I want another specific implementation)

The two logic are in fact "dual": in 1. first I define what my data should be, and then I associate functionality by wrapping around, in 2 I inherit the functionaliy and then define what they are for.
Polimorphism in 1 is based on static_cast and in 2 is based on virtual functions, RTTI and dynamic_cast.


What I don't like is certain sometime "intergralistic" approach: open source must be "template" (because they are source) and "closed source" must be "library" and inheritance (because thay can be compiled separately).

What sometime is forgotten is the "efficency of the process": if everything is in headres, all compiling happens in one place and all symbols must be known to the compiler (and - eventually - skipped because not referenced)
On the other side, if everything is in library, compiling is quite simple and fast, but linking is more difficult. And is the linker to skip the unused code.


In other therm, 1. is heavy for the compilers, 2. is heavy for the linker.
The optimization is probably a balance between the two approaches.

 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值