如何扩展stl类有我自己的方法? [英] How can I extend stl classes to have my own methods?

查看:170
本文介绍了如何扩展stl类有我自己的方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道从stl类继承是一个的想法。但是有没有其他方法来扩展它们?

I know that it is a bad idea to inherit from stl classes. But is there any other way to extend them?

让我们说,为了提高可读性,我希望能够在我的向量上调用一个添加方法,而不是较少可读push_back。

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".

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

Or perhaps I want to add a simple hasKey method to my std::map.

除了创建一个包含std :: vector作为成员的包装器类,将每个函数调用从我的包装传递给向量吗?

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?

推荐答案

您应该使用免费的函数:

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();
}

如果不是necesarry,不要使用继承。这很傻。

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

这篇关于如何扩展stl类有我自己的方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆