温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

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

发布时间:2021-11-24 10:52:49 来源:亿速云 阅读:149 作者:iii 栏目:大数据

本篇内容主要讲解“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++中为什么不要模板化类继承”有了更深的了解,不妨来实际操作一番吧!这里是亿速云网站,更多相关内容可以进入相关频道进行查询,关注我们,继续学习!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

c++
AI