如何检查运算符 != 模板参数是否存在 C++ 17?

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

本文关键字:是否 参数 存在 C++ 何检查 检查 运算符      更新时间:2023-10-16

我有以下用例:

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

只要T提供operator!=实现,它就有效(我想其中一个复杂之处在于operator!=可以作为T的成员函数实现......

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

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 中看到的可选虚拟模板函数参数更容易阅读/理解......

使用检测习惯用语,它非常简单:

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) {
// ...
}
}
相关文章: