[英]std::vector and its iterator as single template typename
In order to get an "easier-to-remember" interface to the index-generating function std::distance(a,b), I came up with the idea of a better distinction of it's arguments (when used against the base of a vector: vec.begin() ) by calling a templated function with the vector and its iterator, like: 为了获得索引生成函数std :: distance(a,b)的“易于记忆”的接口,我提出了更好地区分它的参数的想法(当使用它的基础时vector:vec.begin())通过使用向量及其迭代器调用模板化函数,如:
std::vector<MyType> vect;
std::vector<MyType>::const_iterator iter;
...
...
size_t id = vectorindex_of(iter, vect);
with the rationale of never confusing the order of the arguments ;-) 从不混淆论点顺序的理由;-)
The explicit formulation of the above idea would read sth. 上述观点的明确表述将会读到。 like 喜欢
template <typename T>
inline
size_t vectorindex_of(
typename std::vector<T>::const_iterator iter,
const std::vector<T>& vect ) {
return std::distance( vect.begin(), iter );
}
... which works but looks awkward. ......虽然有效,但看起来很尴尬。
I'd love to have the template mechanism implicitly deduce the types like (pseudo-code): 我希望让模板机制隐式推导出类似(伪代码)的类型:
template <typename T>
inline
size_t vectorindex_of(T::const_iterator iter, const T& vect) {
return std::distance( vect.begin(), iter );
}
... which doesn't work. ......哪个不起作用。 But why? 但为什么?
The fix is easy: add typename
before T::const_iterator iter
. 修复很简单:在T::const_iterator iter
之前添加typename
。 This is needed because class templates may be specialized and using typename
tells the compiler a type name is expected at T::const_iterator
and not a value or something. 这是必需的,因为类模板可能是专用的,并且使用typename
告诉编译器在T::const_iterator
一个类型名称,而不是值或其他东西。
You do the same in your less generic function, too. 您也可以在不太通用的功能中执行相同的操作。
template <typename T>
inline
std::size_t vectorindex_of(typename T::const_iterator iter, const T& vect) {
return std::distance( vect.begin(), iter );
}
Should work fine (notice the typename
). 应该工作正常(注意typename
)。 Template arguments should be deduced in either case. 在任何一种情况下都应该推导出模板参数。
You might also be interested in the "easier-to-remember" way to get the index of a vector iterator: 您可能还对以“更容易记住”的方式获取向量迭代器的索引感兴趣:
i - vec.begin() 我 - vec.begin()
It's identical to pointer arithmetic with random access iterators! 它与使用随机访问迭代器的指针算法完全相同!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.