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

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

本文关键字:constexpr 算法 真的 有用 常不 迭代器 输入 参数      更新时间:2023-10-16

在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容器的情况下有用。有人能澄清我是否遗漏了什么以及我的理解是否正确吗?。

当然是。让我们尝试另一种算法,据我所知,它还不是C++中的constexprstd::iota。但定义一个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);