如何针对多个键类型专门化 std 映射?
我有一个 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()));
}
};
它工作得很好,(不要问为什么我不想使用一些隐式转换,这会导致太多模糊的重载,而且在这种情况下完整转换很昂贵:)
无论如何它都会很好如果上面的内容可以是 std::map 的特化,其中任何
std::map<FancyKey,ValueT> fancymap;
相同的事情
FancyKeyMap<ValueT> fancyMap;
人都可以做与这种类型的特化
?好的,只是尝试了部分专业化:
namespace std {
template<class ValT, class CompareT=FancyKey::Less,
class AllocT=allocator<pair<const FancyKey,ValT> > >
class map<FancyKey, ValT, CompareT, AllocT>
{
....
};
}
我收到此错误:
“部分专业化不允许默认参数”,
但要使其像 std::map 一样,它需要具有“继承的”默认参数和允许它们被覆盖。下一步可能吗?
我确实看到了关于拥有可搜索模板常见问题解答的建议,这似乎是一个非常常见的问题;^>
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 {
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 ;^>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
避免输入
makeKeyRef()
(在find
调用中)并同时更明确地了解意图似乎很麻烦。您是否考虑过进行额外的输入并向未来的维护人员明确您的意图?另外,由于标准容器没有虚拟析构函数,除非您非公开继承,因此当某个容器被基类指针销毁时,您就会面临未定义的行为。
This seems like a lot of trouble to avoid typing
makeKeyRef()
(infind
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.