问题
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()
returnsx == 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()
returnsx == 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