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

时间:2022-07-25
本文章向大家介绍C++核心准则T.80:不要天真地模板化类继承,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

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

  • Flag virtual functions that depend on a template argument. ??? False positives 标记依赖模板参数的虚函数。假阳性。