简体   繁体   English

如何将 std map 专门用于多种密钥类型?

[英]How Can I specialize a std map for multiple key types?

I have a subclass of std::map我有一个 std::map 的子类

template<class ValueT>
FancyKeyMap
    : public std::map<FancyKey,ValueT, FancyKey::Less>
{
     ...
public:
     inline iterator find(FancyKeyArg key)
     {
         return(std::map<FancyKey,ValueT,
                FancyKey::Less>::find(FancyKeyArg.makeKeyRef()));
     }  
};

this works fine, (dont ask why I don't want to use some implicint conversion, this causes too many ambiguous overloads also a full conversion in this case is expensive:)这很好用,(不要问我为什么不想使用一些隐含转换,这会导致太多模棱两可的重载,在这种情况下,完全转换也很昂贵:)

anyway it woudl be nice if the above could be a specialization of std::map where any无论如何,如果上面可以是 std::map 的专业化,那会很好

std::map<FancyKey,ValueT> fancymap;

woudl do the same thing as会做同样的事情

FancyKeyMap<ValueT> fancyMap;

can one do this type of specialization?可以做这种类型的专业化吗?


Ok just tried a partial specialization:好的,只是尝试了部分专业化:

namespace std {

template<class ValT, class CompareT=FancyKey::Less, 
         class AllocT=allocator<pair<const FancyKey,ValT> > >
    class map<FancyKey, ValT, CompareT, AllocT>
{
     ....
};

}

I get this error:我收到此错误:

"default arguments not allowed on a partial specialization" “部分专业化不允许默认 arguments”

but to make it act like std::map it needs to have the "inherited" default args and allow them to be overridden.但要使其表现得像 std::map 它需要具有“继承的”默认参数允许它们被覆盖。 Next step is that possible?下一步可能吗?

I did see a suggestion for having a searchable template FAQ it does seem this is a very common question;^>我确实看到了有关使用可搜索模板常见问题解答的建议,这似乎是一个非常常见的问题;^>

This seems like a lot of trouble to avoid typing makeKeyRef() (in find calls) and being more explicit about the intent at the same time.避免键入makeKeyRef() (在find调用中)并同时更明确地说明意图似乎很麻烦。 Have you considered just doing the extra typing and making your intent clear to future maintainers?您是否考虑过只进行额外的输入并向未来的维护人员表明您的意图?

Also, since standard containers don't have virtual destructors unless you non-publicly inherit you're opening yourself up to undefined behavior when one is destroyed by base class pointer sometime.此外,由于标准容器没有虚拟析构函数,除非您非公开继承,否则当某个容器有时被基本 class 指针销毁时,您将面临未定义的行为。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM