开发者

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

开发者 https://www.devze.com 2023-03-16 14:27 出处:网络
I have a subclass of std::map template<class ValueT> FancyKeyMap : public std::map<FancyKey,ValueT, FancyKey::Less>

I have a subclass of 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<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 {开发者_JAVA技巧

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"

but to make it act like std::map it needs to have the "inherited" default args and allow them to be overridden. 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. 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.

0

精彩评论

暂无评论...
验证码 换一张
取 消