如何使用C++20 concepts表达Compare命名要求以约束自定义排序比较函数
解决方案
你不需要额外单独处理equiv相关的等价关系约束,直接使用std::strict_weak_order即可,它已经完全覆盖了Cppreference中Compare命名要求的所有规则:
std::strict_weak_order的语义定义本身就隐含了:由!comp(a, b) && !comp(b, a)推导出来的关系必须是合法的等价关系,这和你提到的Compare命名要求完全匹配。- 如果你硬要显式校验等价关系的约束,需要传入的关系就是你自己基于comp构造的判断逻辑
[&comp](const auto& a, const auto& b) { return !comp(a, b) && !comp(b, a); },但这个操作完全是冗余的。
最终约束写法
#include <concepts> #include <iterator> template <std::random_access_iterator RandomIt, std::strict_weak_order<std::iter_reference_t<RandomIt>, std::iter_reference_t<RandomIt>> Compare> void sort(RandomIt first, RandomIt last, Compare comp);
注:C++20标准库的
std::sort实现就是用的上述约束,和你的需求完全对齐,可以直接复用。
内容的提问来源于stack exchange,提问作者Touloudou
相关产品推荐
相关产品推荐

