【发布时间】:2019-04-24 14:58:57
【问题描述】:
在 C++ 模板中,我很难用正确的 size_type 定义变量。基本上,这将是容器中的索引类型。我知道int 可以工作,但希望以干净的形式使用它。
template<typename ForwardIt>
void test(ForwardIt it) {
// this yields the underlying type
decltype(typename std::iterator_traits<ForwardIt>::value_type()) T;
// what I would like is something like above, but yielding the
// correct size_type for the container.
// Something like this but with the type extracted from ForwardIt:
std::vector<int>::size_type i;
...
}
【问题讨论】:
-
你想用这个号码做什么?可能你想要
iterator_traits<It>::difference_type?给定一个迭代器,通常你不能索引到容器本身(例如,它可能是一个不支持它的容器)。 -
你可以得到
difference_type。没有办法从迭代器所在的容器中获取size_type -
@NathanOliver - 我认为您的意思是“迭代器”,而不是“容器”
-
@MarshallClow 不,我的意思是容器。 我想要的是类似上面的东西,但是为容器产生 // 正确的 size_type。
标签: c++ stl iterator decltype typename