为了获得索引生成函数std :: distance(a,b)的"易于记忆"的接口,我提出了更好地区分它的参数的想法(当使用它的基础时vector:vec.begin())通过使用向量及其迭代器调用模板化函数,如:
std::vector<MyType> vect;
std::vector<MyType>::const_iterator iter;
...
...
size_t id = vectorindex_of(iter, vect);
Run Code Online (Sandbox Code Playgroud)
从不混淆论点顺序的理由;-)
上述观点的明确表述将会读到.喜欢
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 );
}
Run Code Online (Sandbox Code Playgroud)
......虽然有效,但看起来很尴尬.
我希望让模板机制隐式推导出类似(伪代码)的类型:
template <typename T>
inline
size_t vectorindex_of(T::const_iterator iter, const T& vect) {
return std::distance( vect.begin(), iter );
}
Run Code Online (Sandbox Code Playgroud)
......哪个不起作用.但为什么?
修复很简单:typename之前添加T::const_iterator iter.这是必需的,因为类模板可能是专用的,并且使用typename告诉编译器一个类型名称是预期的T::const_iterator而不是值或什么.
您也可以在不太通用的功能中执行相同的操作.