c++ - 如何静态断言 std::array 类成员在 c++11 中进行排序?

标签 c++ c++11

如何在编译期间断言 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/

相关文章:

c++ - 如何在 C++ 中访问数组结构内部的数组结构?

c++ - 在调用函数的范围内构造返回对象

c++ - 显示 vector C++ 的最小值和最大值

c++11 - 如何将二进制数据写入现代 C++ 中的文件?

c++ - 用户定义的限定符

C++11:使用正则表达式进行两种可能的匹配次数的安全实践

c++ - 在 C++ 中, "class instance"是唯一的对象类型吗?

gcc 4.8.1 : list-initialization for copy constructor doesn't work 中的 C++11

c++ - C++中实现List时在何处声明Node结构

c++ - 具有类内初始化的默认默认构造函数的行为是什么?