且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

用户定义的类作为模板参数

更新时间:2022-01-25 10:11:06

您应该像普通的 std :: map 一样,将比较列为一种类型.也就是说,具有实用程序类 less_compare :

You should factor out the comparison as a type, like the normal std::map does. That is, have a utility class 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 来说,它是小于" someOtherThing.注意,该分解也允许用户定义比较(这就是为什么引用小于"的原因).这就是基于策略的设计.

And to compare two values, do: if (mCompare(someThing, someOtherThing)), which will be true with someThing is "less than" someOtherThing. Note this factoring also allows user-defined comparisons (which is why "less than" is quoted). This is known as policy-based design.

现在您可以仅将C字符串的 less_compare 类专门化.(并且还提供 greater_compare 和亲属.)

And now you can specialize just the less_compare class for C-strings. (And also provide greater_compare and kin.)

请记住,除非这是为了学习,否则您不应该实现自己的地图.还要注意, std :: string operator< 已经过载.

Do keep in mind, unless this is for learning, you should not be implementing your own map. Also note that std::string has operator< overloaded already.