I' m re-implementing std::map
. I need to make sure that any data type (basic or user defined) key will work with it. I declared the Map class as a template which has two parameters for the key and the value. My question is if I need to use a string as the key type, how can I overload the < and > operators for string type keys only?? In template specialization we have to specialize the whole class with the type we need as I understand it.
Is there any way I can do this in a better way?? What if I add a separate Key class and use it as the template type for Key?
问问题
1731 次
2 回答
1
您应该将比较作为一种类型考虑在内,就像正常std::map
情况一样。也就是说,有一个实用程序类less_compare
:
template <typename T>
struct less_compare
{
bool operator()(const T& pLhs, const T& pRhs) const
{
return pLhs < pRhs;
}
};
接着:
template <typename Key, typename Value, typename Compare = less_compare<Key> >
class map
{
// ...
private:
Compare mCompare;
};
并且要比较两个值,请执行:if (mCompare(someThing, someOtherThing))
,这将是真实的someThing
is "less than" someOtherThing
。请注意,此因式分解还允许用户定义的比较(这就是引用“小于”的原因)。这称为基于策略的设计。
现在你可以只专门化less_compare
C 字符串类。(并且还提供greater_compare
和亲属。)
请记住,除非这是为了学习,否则您不应该实现自己的地图。另请注意,std::string
已经operator<
超载。
于 2010-05-20T04:46:23.733 回答
0
你也可以使用类型特征。它将为您提供一个框架来解决类型之间可能的未来差异。
于 2010-05-20T04:51:56.247 回答