问题描述
在c ++ 20中提出,某些算法是constexpr.
proposed in c++ 20, some algorithms are 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容器的情况下有用.有人可以澄清我是否缺少什么,我的理解是否正确?.
While we know iterator are not constexpr generally. I think this is useful only in case of constexpr container. Can someone clarify if I am missing something and Whether my understanding is correct ?.
推荐答案
可以.让我们尝试另一种算法,据我所知,它不是C ++ 20中的 constexpr
.但是定义一个 constexpr
版本并不难(我只是从 cppreference
复制了示例实现,并在其上拍了 constexpr
):
Sure it is. Let's try another algorithm, which is not yet constexpr
in C++20 to my knowledge, std::iota
. But it's not too hard to define a constexpr
version (I just copied the sample implementation from cppreference
and slapped constexpr
on it):
template<class ForwardIterator, class T>
constexpr void my_iota(ForwardIterator first, ForwardIterator last, T value)
{
while(first != last) {
*first++ = value;
++value;
}
}
那么有用吗?是的.只要创建迭代器作为评估常量表达式的一部分,算法的评估就可以出现在常量表达式中.例如:
So is it useful? Yes it is. So long as the iterators are created as part of evaluating a constant expression, the evaluation of the algorithm can appear in a constant expression. For instance:
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
将作为评估的一部分创建,其迭代器也将作为评估的一部分.这些是有效的:
The above creates an array initialized with the iota algorithm. If the function is called as part of evaluating a constant expression, the object ret
is created as part of the evaluation, and so are its iterators. These are valid:
constexpr auto a1 = make_iota_array<10, int>();
constexpr auto a2 = make_iota_array<10>(0u);
这篇关于当迭代器(输入参数)通常不是constexpr时,constexpr算法真的有用吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!