C++中为什么不要模板化类继承

本篇内容主要讲解“C++中为什么不要模板化类继承”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“C++中为什么不要模板化类继承”吧!

亳州网站建设公司创新互联,亳州网站设计制作,有大型网站制作公司丰富经验。已为亳州成百上千提供企业网站建设服务。企业网站搭建\成都外贸网站建设要多少钱,请找那个售后服务好的亳州做网站的公司定做!

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

Reason(原因)

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

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

Example, bad(反面示例)

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

template<typename T>
class Vector : public Container<T> {
public:
   // ...
};

Vector<int> vi;
Vector<string> 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<int>::sort() is called, so it must generate code for it. Similar for vector<string>::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<int>::sort()是否被调用了,因此必须为之生成代码。vector<string>::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(实施建议)

标记依赖模板参数的虚函数。

到此,相信大家对“C++中为什么不要模板化类继承”有了更深的了解,不妨来实际操作一番吧!这里是创新互联网站,更多相关内容可以进入相关频道进行查询,关注我们,继续学习!

当前标题:C++中为什么不要模板化类继承
转载注明:https://www.cdcxhl.com/article36/jghjsg.html

成都网站建设公司_创新互联,为您提供搜索引擎优化品牌网站设计网页设计公司云服务器网站导航静态网站

广告

声明:本网站发布的内容(图片、视频和文字)以用户投稿、用户转载内容为主,如果涉及侵权请尽快告知,我们将会在第一时间删除。文章观点不代表本网站立场,如需处理请联系客服。电话:028-86922220;邮箱:631063699@qq.com。内容未经允许不得转载,或转载时需注明来源: 创新互联

网站托管运营