When to use template vs inheritance

后端 未结 5 1038
自闭症患者
自闭症患者 2020-12-07 12:57

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\". B

5条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-07 13:25

    Templates are appropriate when defining an interface that works on multiple types of unrelated objects. Templates make perfect sense for container classes where its necessary generalize the objects in the container, yet retain type information.

    In case of inheritance, all parameters must be of the defined parameter type, or extend from it. So when methods operate on object that correctly have a direct hierarchical relationship, inheritance is the best choice.

    When inheritance is incorrectly applied, then it requires creating overly complex class hierarchies, of unrelated objects. The complexity of the code will increase for a small gain. If this is the case, then use templates.

提交回复
热议问题