迭代器所指对象的类型,称为该迭代器的value type。
获取迭代器的value type可以使用nested type(内嵌类型)声明。
typedef T value_type; //nested type
#include <iostream>
using namespace std;
template<class T>
class Myiter {
public:
typedef T value_type; //value_type就是Myiter这个迭代器所指对象的类型
T* ptr;
Myiter(T* p = 0):ptr(p){}
T& operator* () const {return *ptr;}
//...
};
template <class I>
typename I::value_type func (I ite) {
return *ite;
}
int main() {
Myiter<int> ite(new int(8));
cout << func(ite) << endl;
}
通过func函数萃取出了迭代器的value type。
- func的入参类型为
Myiter<int>
,也即I
的实例化类型为Myiter<int>
。func的返回值为I
内部的value_type
,也即T
。 *ite
调用类中的*
重载,返回Myiter<int>
中的int
。由此获取到了迭代器的value type。