3

我知道从 stl 类继承是一个坏主意。但是还有其他方法可以扩展它们吗?

假设为了提高可读性,我希望能够在我的向量上调用“add”方法,而不是可读性较差的“push_back”。

或者我想在我的 std::map 中添加一个简单的 hasKey 方法。

除了创建一个以 std::vector 作为成员的整个包装器类,将每个函数调用从我的包装器传递给向量之外,还有什么方法可以做到这一点?

4

2 回答 2

14

You should use free functions:

template<typename... Args>
bool has_key(std::map<Args...> const& map, typename std::map<Args...>::key_type key) {
  return map.find(key) != map.end();
}

Don't use inheritance if it's not necesarry. That's silly.

于 2013-06-04T21:12:24.683 回答
3

Once developers become accustomed to the STL names of things, having changed them will make the code less maintainable. This is generally a bad idea. In practice, since STL classes don't provide a virtual destructor, it's not possible to inherit from them and have good destruction behavior.

于 2013-06-04T21:10:54.203 回答