资讯

精准传达 • 有效沟通

从品牌网站建设到网络营销策划,从策略到执行的一站式服务

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
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(实施建议)

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

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


分享标题:C++中为什么不要模板化类继承
文章路径:http://cdkjz.cn/article/jghjsg.html
多年建站经验

多一份参考,总有益处

联系快上网,免费获得专属《策划方案》及报价

咨询相关问题或预约面谈,可以通过以下方式与我们联系

大客户专线   成都:13518219792   座机:028-86922220