标准库中没有任何东西可以完全满足您的需求,您必须自己提供这样的类。
但是,请注意,从标准库容器(例如std::map)公开继承是一个坏主意;它们不是为此而设计的,它们没有虚拟函数,也没有虚拟析构函数。考虑这个例子,看看为什么这是一个坏主意:
template <class K, class V, class C, class A>
void foo(const std::map<K, V, C, A> &arg)
{
doSomething(arg.at(K()));
}
struct MyMap : std::map<int, int>
{
int at(int) { return 7; }
};
int main()
{
MyMap m;
foo(m); //this will call std::map::at, NOT MyMap::at
}
相反,让您的班级按价值存储std::map(或者可能是std::unordered_map,以更适合您的实施为准)。或者,如果您认为您可以重用许多标准地图的成员函数并且只覆盖一些,您可以非公开地从它继承并仅发布您需要的函数。示例:
template <
class Key,
class Value,
class Comparator = typename std::map<Key, Value>::key_compare,
class Allocator = typename std::map<Key, Value>::allocator_type
>
class DefaultDict : private std::map<Key, Value, Comparator, Allocator>
{
public:
// Publish the clear() function as is
using std::map<Key, Value, Comparator, Allocator>::clear;
// Provide my own at()
Value& at(const Key &key) {
return std::map<Key, Value, Comparator, Allocator>::operator[](key); //call the inherited function
}
// Etc.
};