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

ε祈祈猫儿з 提交于 2021-01-27 04:15:28

问题


proposed in c++ 20, some algorithms are constexpr.

For example:

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)

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 ?.


回答1:


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;
}

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);


来源:https://stackoverflow.com/questions/51491328/is-constexpr-algorithm-really-useful-when-iterator-input-parameters-are-not-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!