用户定义的类作为模板参数 [英] User Defined Class as a Template Parameter

查看:53
本文介绍了用户定义的类作为模板参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在重新实现 std :: map .我需要确保任何数据类型(基本或用户定义的)键都可以使用.我将Map类声明为模板,该模板具有用于键和值的两个参数.我的问题是,是否需要使用字符串作为键类型,如何重载<和>仅适用于字符串类型键的运算符?在模板专门化中,我们必须按照我的理解将整个类专门化为需要的类型.
有什么办法可以更好地做到这一点?如果我添加一个单独的Key类并将其用作Key的模板类型怎么办?

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?

推荐答案

您应该像普通的 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.

这篇关于用户定义的类作为模板参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆