在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 容器的情况下有用。有人可以澄清我是否遗漏了什么以及我的理解是否正确吗?
就是这样。让我们尝试另一种算法,目前还没有constexpr
据我所知,在 C++20 中,std::iota
。但定义一个并不难constexpr
版本(我刚刚复制了示例实现cppreference
并打了耳光constexpr
on it):
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);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)