如何在编译期间断言 std::array<uint8_t, 3>
类成员排序?这将使它成为const
, 使用 static_assert()
而不必打电话 std::sort()
在构造函数中。
在 c++20 中 std::is_sorted()
已成为 constexpr,但不适用于以前的版本。
最佳答案
这是一个可以在 std::array
上直接调用的概念实现证明;让这个更通用(对于其他 constexpr 容器类型)留给读者作为练习:
template <typename T, std::size_t N>
constexpr bool is_sorted(std::array<T, N> const& arr, std::size_t from) {
return N - from == 0 or (arr[from - 1] <= arr[from] and is_sorted(arr, from + 1));
}
template <typename T, std::size_t N>
constexpr bool is_sorted(std::array<T, N> const& arr) {
return N == 0 or is_sorted(arr, 1);
}
关于c++ - 如何静态断言 std::array 类成员在 c++11 中进行排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59613339/