这个问题肯定会让人紧张得喘不过气来,但事实上,没有理由避免从标准容器派生,或者“不必要地增加实体”。最简单、最短的表达是最清晰、最好的。
您确实需要对任何派生类型进行所有通常的注意,但对于来自标准的基类型的情况并没有什么特别之处。重写base成员函数可能很棘手,但对于任何非虚基来说都是不明智的,因此这里没有太多特别之处。如果要添加一个数据成员,如果该成员必须与基库的内容保持一致,则需要考虑切片问题,但这同样适用于任何基库。
The place where I have found deriving from a standard container particularly useful is to add a single constructor that does precisely the initialization needed, with no chance of confusion or hijacking by other constructors. (I'm looking at you, initialization_list constructors!) Then, you can freely use the resulting object, sliced -- pass it by reference to something expecting the base, move from it to an instance of the base, what have you. There are no edge cases to worry about, unless it would bother you to bind a template argument to the derived class.
在c++ 20中,这种技术将立即发挥作用的地方是预留。我们可能在哪里写过
std::vector<T> names; names.reserve(1000);
我们可以说
template<typename C>
struct reserve_in : C {
reserve_in(std::size_t n) { this->reserve(n); }
};
然后,即使作为班级成员,
. . .
reserve_in<std::vector<T>> taken_names{1000}; // 1
std::vector<T> given_names{reserve_in<std::vector<T>>{1000}}; // 2
. . .
(根据首选项),而不需要编写构造函数来调用reserve()。
(The reason that reserve_in, technically, needs to wait for C++20 is that prior Standards don't require the capacity of an empty vector to be preserved across moves. That is acknowledged as an oversight, and can reasonably be expected to be fixed as a defect in time for '20. We can also expect the fix to be, effectively, backdated to previous Standards, because all existing implementations actually do preserve capacity across moves; the Standards just haven't required it. The eager can safely jump the gun -- reserving is almost always just an optimization anyway.)
有些人会认为,reserve_in的情况最好由一个免费的函数模板来实现:
template<typename C>
auto reserve_in(std::size_t n) { C c; c.reserve(n); return c; }
这样的替代方案当然是可行的——有时甚至会因为RVO而快得无限大。但是推导或自由函数的选择应该根据其本身的优点,而不是根据对从标准组件推导的毫无根据的迷信。在上面的例子中,只有第二种形式可以使用free函数;尽管在类上下文之外,它可以写得更简洁一点:
auto given_names{reserve_in<std::vector<T>>(1000)}; // 2