首页 文章详情

C++核心准则T.80:不要天真地模板化类继承

面向对象思考 | 452 2020-09-19 00:44 0 0 0
UniSMS (合一短信)

T.80: Do not naively templatize a class hierarchy

T.80:不要天真地模板化类继承


Reason(原因)

Templating a class hierarchy that has many functions, especially many virtual functions, can lead to code bloat.

模板化包含很多成员函数,特别是虚函数的类继承层次会导致代码膨胀。


Example, bad(反面示例)

template
struct Container { // an interface
virtual T* get(int i);
virtual T* first();
virtual T* next();
virtual void sort();
};

template
class Vector : public Container {
public:
// ...
};

Vector vi;
Vector vs;

It is probably a bad idea to define a sort as a member function of a container, but it is not unheard of and it makes a good example of what not to do.

为容器定义一个排序成员函数几乎肯定就是一个坏主意,但这并非没有先例,可以当作说明我们不应该做什么的好例子。

Given this, the compiler cannot know if vector::sort() is called, so it must generate code for it. Similar for vector::sort(). Unless those two functions are called that's code bloat. Imagine what this would do to a class hierarchy with dozens of member functions and dozens of derived classes with many instantiations.

编辑器接受这段代码时,无法知道vector::sort()是否被调用了,因此必须为之生成代码。vector::sort()的情况也一样。只要这两个函数没有被调用,这就是一种代码膨胀。想象一下:这种情况如果发生在一个包含数十个成员函数和被多次例示的数十个派生类的继承结构时会发生什么。


Note(注意)

In many cases you can provide a stable interface by not parameterizing a base; see "stable base" and OO and GP

在很多情况下,你可以在不必参数化基类的情况下提供稳定的接口;参见“稳定的基类和OO and GP


Enforcement(实施建议)

  • Flag virtual functions that depend on a template argument. ??? False positives

    标记依赖模板参数的虚函数。???假阳性。


原文链接

https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#t80-do-not-naively-templatize-a-class-hierarchy


新书介绍

《实战Python设计模式》是作者最近出版的新书,拜托多多关注!

本书利用Python 的标准GUI 工具包tkinter,通过可执行的示例对23 个设计模式逐个进行说明。这样一方面可以使读者了解真实的软件开发工作中每个设计模式的运用场景和想要解决的问题;另一方面通过对这些问题的解决过程进行说明,让读者明白在编写代码时如何判断使用设计模式的利弊,并合理运用设计模式。

对设计模式感兴趣而且希望随学随用的读者通过本书可以快速跨越从理解到运用的门槛;希望学习Python GUI 编程的读者可以将本书中的示例作为设计和开发的参考;使用Python 语言进行图像分析、数据处理工作的读者可以直接以本书中的示例为基础,迅速构建自己的系统架构。




觉得本文有帮助?请分享给更多人。

关注微信公众号【面向对象思考】轻松学习每一天!

面向对象开发,面向对象思考!



good-icon 0
favorite-icon 0
收藏
回复数量: 0
    暂无评论~~
    Ctrl+Enter