[英]Why is std::common_iterator just std::forward_iterator?
[英]Example of use of std::forward_iterator
我有一个看起来像这样的compute
function:
template <typename PayloadType, complex ValueType>
static void comupte_everything(
const typename std::vector<DataPointWithAverage<PayloadType, ValueType>>::iterator begin,
const typename std::vector<DataPointWithAverage<PayloadType, ValueType>>::iterator end)
我想扩展 function 以便它可以接受任何迭代器而不仅仅是向量,我正在尝试使用std::forward_iterator
来做到这一点:
template <typename PayloadType, complex ValueType,
std::forward_iterator<DataPointWithAverage<PayloadType, ValueType>> Iterator>
static void comupte_everything(
const Iterator begin,
const Iterator end)
现在,编译器抱怨我给 forward_iterator 太多了 arguments。
我该如何正确使用它?
如果您想要一种迭代特定类型范围(由模板参数定义)的算法,那么您应该提出要求。
template typename PayloadType, complex ValueType, <std::forward_iterator It, std::sentinel_for<It> Sent>
requires std::same_as<std::iter_value_t<It>, DataPointWithAverage<PayloadType, ValueType>>
static void compute_everything(It start, Sent end)
{
}
std::forward_iterator
是一个概念,不是模板,所以不能像模板一样使用,如果想约束iterator的value_type
,那么可以
template<typename T>
constexpr bool is_DataPointWithAverage = false;
template<typename PayloadType, complex ValueType>
constexpr bool is_DataPointWithAverage<
DataPointWithAverage<PayloadType, ValueType>> = true;
template <std::forward_iterator I>
requires is_DataPointWithAverage<std::iter_value_t<I>>
static void comupte_everything(I begin, I end);
这将限制I
必须 model forward_iterator
,它的value_type
必须是DataPointWithAverage
的特化。
请注意,C++20 中range
的begin()
和end()
可以返回不同的类型,因此更通用的声明应该是
template <std::forward_iterator I, std::sentinel_for<I> S>
requires is_DataPointWithAverage<std::iter_value_t<I>>
static void comupte_everything(I begin, S end);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.