如何检查运算符 != 模板参数是否存在 C++ 17?
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!=
可以作为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) {
// ...
}
}
相关文章:
- 是否有C++编译器选项允许激进地删除所有函数调用,并将参数传递给具有空体的函数
- 是否可以对零模板参数进行模板专门化
- 函数作为模板参数,是否对返回类型强制约束
- visual是否可以在c++中创建一个接收无限数量相同类型(或至少相当数量)参数的函数
- 函数是否可以访问传递给main()的参数
- 在C++中,使用带有 std::optional 参数的函数<T>来表示可选参数是否有意义?
- 如何检查给定的参数是否为 cv::noArray()?
- 表达式 SFINAE:如何根据类型是否包含具有一个或多个参数的函数来选择模板版本
- 如果返回 -1,时间() 的参数是否被修改?
- 用于检查值是否为其任何参数的帮助程序函数
- 将类型声明为类型模板参数的模板参数的一部分是否合法?
- 模板化检查是否存在带有参数列表的类成员函数?
- 我如何知道作为参数的size_t在函数中是否有效?
- 是否可以在C++中有一个"generic"模板参数,该参数可以是非类型模板参数或类型?
- 是否可以就地构造一个固定大小的数组作为函数参数?
- C++方法是否可以根据传递给构造函数的参数具有不同的返回类型?
- 是否可以在运行时强制转换模板参数?
- 是否可以在不填充自己的参数的情况下将模板函数作为参数传递?
- 编译器是否强制根据模板参数计算表达式?
- C++中大多数/所有 setter 函数的参数是否应该写为常量引用?