std::vector 及其迭代器作为单个模板类型名
为了获得“更容易记住”的界面 索引生成函数 std::distance(a,b),我想到了 更好地区分其论点的想法 (当针对向量的基数使用时: vec.begin() ) 通过使用向量调用模板化函数 及其迭代器,例如:
std::vector<MyType> vect;
std::vector<MyType>::const_iterator iter;
...
...
size_t id = vectorindex_of(iter, vect);
其基本原理是永远不要混淆 论点;-)
上述想法的明确表述将 读某事。就像
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 );
}
......这有效但看起来很尴尬。
我希望模板机制能够隐式推断出类型 就像(伪代码):
template <typename T>
inline
size_t vectorindex_of(T::const_iterator iter, const T& vect) {
return std::distance( vect.begin(), iter );
}
...这不起作用。但为什么?
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::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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
修复方法很简单:在
T::const_iterator iter
之前添加typename
。这是必需的,因为类模板可能是专门化的,并且使用typename
告诉编译器在T::const_iterator
中需要类型名称,而不是值或其他内容。您也在不太通用的函数中执行相同的操作。
The fix is easy: add
typename
beforeT::const_iterator iter
. This is needed because class templates may be specialized and usingtypename
tells the compiler a type name is expected atT::const_iterator
and not a value or something.You do the same in your less generic function, too.
应该可以正常工作(注意
typename
)。在任何一种情况下都应该推导模板参数。Should work fine (notice the
typename
). Template arguments should be deduced in either case.您可能还对获取向量迭代器索引的“更容易记住”的方法感兴趣:
i - vec.begin()
它与随机访问迭代器的指针算术相同!
You might also be interested in the "easier-to-remember" way to get the index of a vector iterator:
i - vec.begin()
It's identical to pointer arithmetic with random access iterators!