模板类对象的比较器,C++
让我们拥有由模板对象集表示的新用户类型 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以采用一种方式或另一种方式,这取决于品味。
但是,在第二种情况下,您应该像这样使用它:
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:
我会将比较器移至 TList 类。
由于它没有状态,因此将其设为静态函数会更简单:
I would move comparator to TList class.
And since it has no state, it's simpler to make it a static function:
通常,您会使用模板化成员函数,因为每次要引用它时都编写
有何意义?Typically, you would use the templated member function, because what's the point of writing
<T>
every time you want to refer to it?