【发布时间】:2018-02-23 17:51:32
【问题描述】:
在我的代码中,如果一个对象小于另一个对象,我希望一个操作先于另一个操作发生。但是,如果类型不可比较,则顺序无关紧要。为此,我尝试使用 SFINAE:
template<typename T, typename = decltype(std::declval<std::less<T>>()(std::declval<T>(), std::declval<T>()))>
bool ComparableAndLessThan(const T& lhs, const T& rhs) {
return std::less<T>()(lhs, rhs);
}
bool ComparableAndLessThan(...) {
return false;
}
struct foo {};
int main()
{
foo a,b;
if (ComparableAndLessThan(a, b)) {
std::cout << "a first" << std::endl;
} else {
std::cout << "b first" << std::endl;
}
}
但是这不起作用。如果我创建一个对象而不给它一个 operator
error C2678: binary '<': no operator found which takes a left-hand operand of type 'const foo' (or there is no acceptable conversion)
note: could be 'bool std::operator <(const std::error_condition &,const std::error_condition &) noexcept'
note: or 'bool std::operator <(const std::error_code &,const std::error_code &) noexcept'
note: while trying to match the argument list '(const foo, const foo)'
note: while compiling class template member function 'bool std::less<T>::operator ()(const _Ty &,const _Ty &) const'
with
[
T=foo,
_Ty=foo
]
我假设因为声明存在,SFINAE 不会将此视为错误,即使实现会导致错误。有什么方法可以检查 std::less 是否可以用于模板类型?
【问题讨论】:
-
哎呀
void main()。哈,它以void test4()开头,但我在重命名时并没有考虑。编辑代码以使用 int 代替。