问题描述
我一直在寻找这个,对此的共同反应似乎是它们无关,一个不能代替另一个".但是假设你在接受采访时被问到你什么时候会使用模板而不是继承,反之亦然?"
I've been looking around for this one, and the common response to this seems to be along the lines of "they are unrelated, and one can't be substituted for the other". But say you're in an interview and get asked "When would you use a template instead of inheritance and vice versa?"
推荐答案
在我看来,模板和继承实际上是正交的概念:继承是垂直的",并且向下,从抽象到越来越具体.一个形状,一个三角形,一个等边三角形.
The way I see it is that templates and inheritance are literally orthogonal concepts: Inheritance is "vertical" and goes down, from the abstract to the more and more concrete. A shape, a triange, an equilateral triangle.
另一方面,模板是水平的",定义了并行代码的实例,彼此一无所知.整数排序与双精度排序和字符串排序在形式上是相同的,但它们是三个完全不同的函数.从远处看,它们都看起来"一样,但它们却没有任何关系.
Templates on the other hand are "horizontal" and define parallel instances of code that knowns nothing of each other. Sorting integers is formally the same as sorting doubles and sorting strings, but those are three entirely different functions. They all "look" the same from afar, but they have nothing to do with each other.
继承提供运行时抽象.模板是代码生成工具.
Inheritance provides runtime abstraction. Templates are code generation tools.
因为这些概念是正交的,所以它们可以愉快地一起使用以实现共同的目标.我最喜欢的例子是类型擦除,其中类型擦除容器包含一个指向实现类的虚拟基指针,但是有任意多个由模板派生类生成的具体实现.模板代码生成用于填充继承层次结构.魔法.
Because the concepts are orthogonal, they may happily be used together to work towards a common goal. My favourite example of this is type erasure, in which the type-erasing container contains a virtual base pointer to an implementation class, but there are arbitrarily many concrete implementations that are generated by a template derived class. Template code generation serves to fill an inheritance hierarchy. Magic.
这篇关于何时使用模板 vs 继承的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!