你宁愿不从标准容器继承,它们不是为它设计的。
此外,如前所述,要使包含的比较行为多态,您需要存储引用或指针。使用指针要简单得多。
为了避免担心释放内存,请使用智能指针(std::unique_ptr 或 std::shared_ptr)。
以下片段显示了上述大部分内容的工作原理,包括如何在您自己的容器类 ( RC<>
) 上进行统一初始化:
#include <unordered_map>
#include <memory>
struct Comparison {};
template <class T> struct Equal_to : Comparison { };
template <class T> struct Not_equal_to : Comparison { };
template <class T> struct Greater : Comparison { };
template <class T,class V>
class RC
{
typedef std::unordered_map<T,V> comps_t;
typedef typename comps_t::value_type value_type;
comps_t comps;
public:
RC(std::initializer_list<value_type> init) : comps(init) { }
};
int main(int argc, const char *argv[])
{
RC<std::shared_ptr<Comparison>, int> demo = {
{ std::make_shared<Equal_to<int>>(),10 },
{ std::make_shared<Not_equal_to<int>>(),30 },
{ std::make_shared<Greater<int>>(),20 } };
return 0;
}
在(可能无用的优化方面,如果它与您的其他构造函数需求不冲突,您可以拥有一个完美的转发构造函数。这将有利于正确支持移动语义:
template <typename... A>
RC(A&&... a) : comps(std::forward<A...>(a...)) { }