【问题标题】:Is std::equal_to guaranteed to call operator== by default?std::equal_to 是否保证默认调用 operator== ?
【发布时间】:2013-02-27 21:06:14
【问题描述】:

我一直认为标准要求std::equal_to<T> 的非专业模板调用T::operator==,但我注意到description at cppreference.com 几乎暗示它是相反的;当然,它没有将其作为要求提及。我还检查了 C++11 草案标准 N3337,也找不到任何保证。

如果您使用operator== 创建一个类,您希望它可以在所有情况下使用。

老实说,我想不出一种实现std::equal_to 的方法,但这种方法不会起作用,但我错过了什么吗?

【问题讨论】:

  • std::less 在指针的情况下与operator< 的行为不同。
  • cppreference.com上的描述很清楚...
  • 页面描述有问题。描述可以改进为:为类型 T 实现一个调用 operator== 的函子(缺少的 a 函子是混乱的根源)
  • @AlexChamberlain:我不太同意你的说法......这句话 Implements operator== on type T 有点误导
  • @MarkRansom 这是一个维基;那是我的第一次编辑。

标签: c++ std comparison-operators


【解决方案1】:

std::equal_to 是否保证默认调用operator ==

是的

如果没有专门化,equal_to 的调用运算符将​​调用operator ==。来自 C++11 标准的第 20.8.5 段:

1 该库为该语言(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() 返回x == y

【讨论】:

  • 呸,你追我的名声太快了!
  • @sftrabbit:不是真的,在我看来差异总是相同的 5.2k ;-)
  • 我很自然地看到了标准的那部分,但我想我只是错过了他们试图用简单的语言表达的内容。
【解决方案2】:

std::equal_to 定义为:

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() 返回x == y

所以是的,如果T 是一个类类型,并且为它定义了operator== 重载作为左操作数,它将被使用。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-09-19
    • 1970-01-01
    • 2016-12-14
    • 2023-02-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多