模板类对象的比较器,C++

发布于 2024-10-10 00:34:14 字数 749 浏览 0 评论 0原文

让我们拥有由模板对象集表示的新用户类型 Tlist:

template <class T>
struct TList
{
    typedef std::set <Object <T>, sortByVal >   TObjects;     
};

比较器 sortByVal 必须也是模板类,还是非模板类的模板方法就足够了?

class sortByVal 
{
    public:
        template <class T>
        bool operator() ( const Object  <T> &o1, const Object  <T> &o2 ) const
        {
            return o1.getVal() < o2.getVal();
        }
};

或者

template <class T>
class sortByVal 
{
    public:
        bool operator() ( const Object  <T> &o1, const Object  <T> &o2 ) const
        {
            return o1.getVal() < o2.getVal();
        }
};

Let us have the new user type Tlist represented by the set of template objects:

template <class T>
struct TList
{
    typedef std::set <Object <T>, sortByVal >   TObjects;     
};

Must be the comparator sortByVal also template class or it is sufficient a template method of the non-template class?

class sortByVal 
{
    public:
        template <class T>
        bool operator() ( const Object  <T> &o1, const Object  <T> &o2 ) const
        {
            return o1.getVal() < o2.getVal();
        }
};

or

template <class T>
class sortByVal 
{
    public:
        bool operator() ( const Object  <T> &o1, const Object  <T> &o2 ) const
        {
            return o1.getVal() < o2.getVal();
        }
};

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

葮薆情 2024-10-17 00:34:14

您可以采用一种方式或另一种方式,这取决于品味。

但是,在第二种情况下,您应该像这样使用它:

typedef std::set <Object <T>, sortByVal<T> >   TObjects;

You can do it one way or the other, it's a matter of taste.

However, in the second case, you should use it like this:

typedef std::set <Object <T>, sortByVal<T> >   TObjects;
帅冕 2024-10-17 00:34:14

我会将比较器移至 TList 类。
由于它没有状态,因此将其设为静态函数会更简单:

template<typename T>
struct TList
{
    static bool Compare(const TObject<T> &o1,const TObject<T> &o2);
...

I would move comparator to TList class.
And since it has no state, it's simpler to make it a static function:

template<typename T>
struct TList
{
    static bool Compare(const TObject<T> &o1,const TObject<T> &o2);
...
萝莉病 2024-10-17 00:34:14

通常,您会使用模板化成员函数,因为每次要引用它时都编写 有何意义?

Typically, you would use the templated member function, because what's the point of writing <T> every time you want to refer to it?

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文