8

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

4

1 回答 1

7

是的。让我们尝试另一种算法,据我所知,它还没有constexpr在 C++20 中,std::iota. 但是定义一个版本并不难constexpr(我只是从中复制了示例实现cppreferenceconstexpr对其进行了处理):

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);
于 2018-07-24T08:12:39.527 回答