How can I extend stl classes to have my own methods? [duplicate]

て烟熏妆下的殇ゞ 提交于 2020-01-21 15:12:08

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!