问题
I know that it is a bad idea to inherit from stl classes. But is there any other way to extend them?
Let's say that to improve readability, I wanted to be able to call an "add" method on my vectors instead of the less readable "push_back".
Or perhaps I want to add a simple hasKey method to my std::map.
Is there any way that I could do that, aside from creating an entire wrapper class with a std::vector as a member, passing each function call from my wrapper to the vector?
回答1:
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.
回答2:
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.
来源:https://stackoverflow.com/questions/16927464/how-can-i-extend-stl-classes-to-have-my-own-methods