当迭代器(输入参数)通常不是 constexpr 时,constexpr 算法真的有用吗?

is constexpr algorithm really useful, when iterator (input parameters) are not constexpr generally?

在c++20中提出,部分算法是constexpr。

例如:

template< class InputIt, class UnaryPredicate >
bool all_of( InputIt first, InputIt last, UnaryPredicate p );
(since C++11)
(until C++20)


template< class InputIt, class UnaryPredicate >
constexpr bool all_of( InputIt first, InputIt last, UnaryPredicate p );
(since C++20)

虽然我们知道迭代器通常不是constexpr。我认为这仅在 constexpr 容器的情况下有用。有人可以澄清我是否遗漏了什么以及我的理解是否正确吗?

当然是。让我们尝试另一种算法,据我所知 std::iota 在 C++20 中还没有 constexpr。但是定义一个 constexpr 版本并不难(我只是从 cppreference 复制了示例实现并在其上打了 constexpr ):

template<class ForwardIterator, class T>
constexpr void my_iota(ForwardIterator first, ForwardIterator last, T value)
{
    while(first != last) {
        *first++ = value;
        ++value;
    }
}

那么有用吗?是的。只要迭代器是作为计算常量表达式的一部分创建的,算法的计算就可以出现在常量表达式中。例如:

template<std::side_t N, typename T>
constexpr make_iota_array(T start = {}) {
  std::array<T, N> ret{};
  my_iota(ret.begin(), ret.end(), start);
  return ret;
}

上面创建了一个用iota算法初始化的数组。如果调用函数作为计算常量表达式的一部分,则对象 ret 将作为计算的一部分创建,它的迭代器也是如此。这些是有效的:

constexpr auto a1 = make_iota_array<10, int>();
constexpr auto a2 = make_iota_array<10>(0u);