在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)
Run Code Online (Sandbox Code Playgroud)
虽然我们知道迭代器通常不是constexpr.我认为这只适用于constexpr容器.有人可以澄清我是否遗漏了某些内容以及我的理解是否正确?
当然是啦.让我们尝试另一种算法,据constexpr我所知,这还没有在C++ 20中std::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;
}
}
Run Code Online (Sandbox Code Playgroud)
它有用吗?是的.只要迭代器是作为评估常量表达式的一部分创建的,算法的评估就会出现在常量表达式中.例如:
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;
}
Run Code Online (Sandbox Code Playgroud)
上面创建了一个用iota算法初始化的数组.如果在评估常量表达式时调用该函数,则该对象ret将作为求值的一部分创建,其迭代器也是如此.这些是有效的:
constexpr auto a1 = make_iota_array<10, int>();
constexpr auto a2 = make_iota_array<10>(0u);
Run Code Online (Sandbox Code Playgroud)