当迭代器(输入参数)通常不是constexpr时,constexpr算法真的有用吗
is constexpr algorithm really useful, when iterator (input parameters) are not constexpr generally?
在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容器的情况下有用。有人能澄清我是否遗漏了什么以及我的理解是否正确吗?。
当然是。让我们尝试另一种算法,据我所知,它还不是C++中的constexpr
,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;
}
}
那么它有用吗?是的。只要迭代器是作为计算常量表达式的一部分创建的,算法的计算就可以出现在常量表达式中。例如:
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);
相关文章:
- lambda参数转换为constexpr技巧,然后获取带链接的数组
- 为什么这个运算符<重载函数对 STL 算法不可见?
- 多成员Constexpr结构初始化
- 基于ELO的团队匹配算法
- C++选择排序算法中的逻辑错误
- 条件constexpr函数
- 有没有办法将谓词中的元素偏移量传递给 std 算法?
- constexpr 函数中的非文字(通过 std::is_constant_evaluated)
- C++A*算法并不总是在路径中具有目标节点
- 排序算法c++
- Visual C++ constexpr Hints
- 如何确认我的constexpr表达式实际上已经在编译时执行
- 为什么constexpr的性能比正常表达式差
- 构建可组合有向图(扫描仪生成器的汤普森构造算法)
- 是否可以使用if constexpr删除控制流语句
- 要与"if constexpr"一起使用的编译时消息(在预处理器之后)
- 为什么std::isnan 不是 constexpr?
- 算法问题:查找从堆栈中弹出的所有序列
- 当迭代器(输入参数)通常不是constexpr时,constexpr算法真的有用吗
- 对jesteres哈希算法进行constexpr