在许多情况下,问题甚至没有问自己,因为有时继承提供了模板无法提供的必要功能。例如,当我需要通过一个基类型(多态)处理不同的类型时,我需要使用继承。
In many situations, the question doesn't even ask itself, since sometimes inheritance provides necessary features which templates can't provide. For example, when I need to address different types via one base-type (polymorphism), I need to use inheritance.
但是,有些情况下问题可以解决用继承和模板来解决。
However, there are some instances where the problem can be solved both with inheritance, as well as templates.
以代码的某些部分为例进行策略模式参数化:
Take for example strategy pattern-like parametrization of certain parts of the code:
文件的一个解决方案-parser可能如下所示:
One solution of a file-parser could look like this:
class FileParser { //... public: void Parse(ParsingAlgorithm* p); //... } void FileParser::Parse(ParsingAlgorithm* p) { m_whatevertypeofvaluesineed = p->Parse(whateverparametersyouneed); }其中ParsingAlgorithm是一个抽象基类,它提供了一些基本方法和需求由任何喜欢为FileParser类实现特定解析器的人继承。
where ParsingAlgorithm is an abstract base class, which provides some basic methods and needs to be inherited by whoever likes to implement a specific parser for the FileParser class.
但是,使用模板可以轻松实现相同目的:
However, the same can easily be achieved using templates:
template <class Parser> class FileParser { //... public: void Parse() { m_whatevertypeofvaluesineed = m_parser.Parse(whateverparametersyouneed); } private: Parser m_parser; //... }我是否有一些一般规则可以用来决定是使用模板还是继承?或者我应该尽可能简单地使用模板,以避免虚函数之类的运行时开销?
Are there some general rules that I can use to decide whether to use templates or inheritance? Or should I simply use templates wherever possible, in order to avoid run-time overhead of things like virtual functions?
推荐答案如果你在编译时知道你将要操作的对象,然后使用模板的静态多态通常是最快的方法,并且它产生的代码更简洁(不需要显式继承)。它也可以更通用,因为您不限于强类层次结构。
If you know during compile-time what objects you're going to manipulate, then static polymorphism with templates is often the fastest way to go, and it produces code that's a little bit more concise (no need for explicit inheritance). It can also be more generic as you're not restricted to a strong class hierarchy.
如果您想要运行时多态,那么您别无选择,只能使用指针,继承和虚函数的轻微开销。
If you want run-time polymorphism, then you have no choice but to use pointers, inheritance and the slight overhead of virtual functions.
我自己的观点:
- 尽可能使用模板,这很舒服
- 使用继承来分解代码(但不要使用异构集合),但要小心切片。
- 不要担心虚拟调用的性能问题
- 有时候你没有选择,你想要使用指针拖拽异类收藏
- Use templates when possible, it's comfortable
- Use inheritance to factorise code (but not to have heterogenous collections), but be careful with slicing.
- Don't worry about the performance issues of virtual calls
- Sometimes you have no choice and you want hetergenous collections dragging around the pain of using pointers
更多推荐
我什么时候应该使用模板而不是继承,反之亦然?
发布评论