Is std::equal_to guaranteed to call operator== by default?

|▌冷眼眸甩不掉的悲伤 提交于 2019-12-22 18:34:44

问题


I had always thought that the standard required the non-specialized template for std::equal_to<T> to call T::operator==, but I noticed the description at cppreference.com almost implies it's the other way around; certainly it doesn't mention it as a requirement. I also checked the C++11 draft standard N3337 and couldn't find any guarantees there either.

If you create a class with an operator== you'd hope it would get used in all circumstances.

I can't honestly think of a way to implement std::equal_to that wouldn't work this way, but am I missing something?


回答1:


Is std::equal_to guaranteed to call operator == by default?

Yes.

If not specialized, equal_to's call operator will invoke operator ==. From Paragraph 20.8.5 of the C++11 Standard:

1 The library provides basic function object classes for all of the comparison operators in the language (5.9, 5.10).

template <class T> struct equal_to 
{
    bool operator()(const T& x, const T& y) const;
    typedef T first_argument_type;
    typedef T second_argument_type;
    typedef bool result_type;
};

2 operator() returns x == y.




回答2:


std::equal_to is defined as:

template <class T> struct equal_to {
  bool operator()(const T& x, const T& y) const;
  typedef T first_argument_type;
  typedef T second_argument_type;
  typedef bool result_type;
};

operator() returns x == y.

So yes, if T is a class type with an operator== overload defined for it as the left operand, it will be used.



来源:https://stackoverflow.com/questions/15122410/is-stdequal-to-guaranteed-to-call-operator-by-default

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!