【发布时间】:2020-10-29 01:54:37
【问题描述】:
例如std::less的比较被定义为模板结构
template< class T = void >
struct less;
虽然std::compare_three_way 被定义为一个普通的结构,它的operator() 是一个模板函数。 (来自 MSVC 的代码)
struct compare_three_way {
template <class _Ty1, class _Ty2>
requires three_way_comparable_with<_Ty1, _Ty2> // TRANSITION, GH-489
constexpr auto operator()(_Ty1&& _Left, _Ty2&& _Right) const
noexcept(noexcept(_STD forward<_Ty1>(_Left) <=> _STD forward<_Ty2>(_Right))) /* strengthened */ {
return _STD forward<_Ty1>(_Left) <=> _STD forward<_Ty2>(_Right);
}
using is_transparent = int;
};
那么为什么std::compare_three_way 不是模板结构呢?
template <class _Ty1, class _Ty2>
requires three_way_comparable_with<_Ty1, _Ty2>
struct compare_three_way {
constexpr auto operator()(_Ty1&& _Left, _Ty2&& _Right) const;
};
顺便说一句,我可以在我自己的容器实现中将std::less<T> 替换为std::three_way_compare,比如C# 中的Comparer<T>。
【问题讨论】:
-
您希望它成为类模板而不是使运算符模板化有什么特别的原因吗?还是您在问为什么不一致?
-
@chris 在模板中使用,如
std::less<T>instd::set<T> -
我认为 std::less
是历史性的,这就是为什么自 c++14 以来,有一个 专业化,这意味着你真的不需要提供 T , T 可以从参数推导中推导出来。 -
std::less<T>为您提供了一种能够比较Ts 的类型。std::compare_three_way为您提供了一种能够比较Ts 的类型。 (std::less<>还为您提供了一种能够比较Ts 的类型。)容器需要能够比较Ts 的东西。这里有一个错误的假设。