問題描述
我一直在尋找這個,對此的共同反應(yīng)似乎是它們無關(guān),一個不能代替另一個".但是假設(shè)你在接受采訪時被問到你什么時候會使用模板而不是繼承,反之亦然?"
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.
另一方面,模板是水平的",定義了并行代碼的實例,彼此一無所知.整數(shù)排序與雙精度排序和字符串排序在形式上是相同的,但它們是三個完全不同的函數(shù).從遠處看,它們都看起來"一樣,但它們卻沒有任何關(guān)系.
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.
因為這些概念是正交的,所以它們可以愉快地一起使用以實現(xiàn)共同的目標.我最喜歡的例子是類型擦除,其中類型擦除容器包含一個指向?qū)崿F(xiàn)類的虛擬基指針,但是有任意多個由模板派生類生成的具體實現(xiàn).模板代碼生成用于填充繼承層次結(jié)構(gòu).魔法.
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.
這篇關(guān)于何時使用模板 vs 繼承的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!