如何使用 C++ 17 检查 operator != 是否存在模板参数?

How to check for operator != existence for template arguments with C++ 17?

我有以下用例:

template<typename T>
struct Foo
{
  bool setValue(T const &iValue)
  {
    if(fValue != iValue)
    {
      fValue = iValue;
      return true;
    }
    return false;
  }

  T fValue;
};

仅在 T 提供 operator!= 实现时才有效(我认为其中一个复杂因素是 operator!= 可以作为 [=12= 的成员函数实现] 或不...).

理想情况下,我想使用 C++ 17 if constexpr 语法编写类似这样的东西

template<typename T>
struct Foo
{
  bool setValue(T const &iValue)
  {
    if constexpr (is_diff_operator_defined<T>::value) {
      if(fValue != iValue)
      {
        fValue = iValue;
        return true;
      }
    } else {
        fValue = iValue;
        return true;
    }
    return false;
  }

  T fValue;
};

我该怎么做?请注意,我使用的是 C++ 17,所以更喜欢使用最新和最强大功能的解决方案(例如 if constexpr,这使得代码比我们通常在 sfinae 中看到的可选虚拟模板函数参数更容易 read/comprehend ...)

有了检测惯用语就很简单了:

template<typename T>
using operator_not_eq_t = decltype(std::declval<T const&>() != std::declval<T const&>());

template<typename T>
constexpr auto is_diff_operator_defined = is_detected_v<operator_not_eq_t, T>;

然后只需像您写的那样将它与 if constexpr 一起使用。 (减去 ::value

请注意,使用概念,您可以简单地内联执行此操作:

if constexpr (requires { fValue != iValue; }) {
    if (fValue != iValue) {
        // ...
    }
}