【问题标题】:Type of Vector's Elements for Use in Iterator Type用于迭代器类型的向量元素类型
【发布时间】:2017-09-27 22:22:35
【问题描述】:

如果我有一个结构 s:

template<typename T>
struct s {
    std::vector<T> list;
};

在main() 中定义为:

s<long double> x;

我尝试使用以下方法获取 list 的迭代器类型:

typedef typename std::vector<decltype(x.list[0])>::iterator IT;

GCC 7.2.1 产生了一堆错误,开头是:

/usr/include/c++/7/bits/alloc_traits.h:392:27: error: forming pointer to reference type 'long double&'
    using pointer = _Tp*;
                        ^

我怀疑 GCC 中 C++ 的底层实现有什么问题,这个错误似乎表明了这一点。

使用此方法还假定 list 不为空,因此我尝试使用 ::value_type(如其他 SO 答案中所建议的那样):

typedef typename std::vector<x.list::value_type>::iterator IT;

GCC 再次产生错误:

error: the value of 'x' is not usable in a constant expression.
    typedef typename std::vector<x.list::value_type>::iterator IT;
                                   ^~~~

为了找到替代方案,我在结构中添加了一个类型保持变量:

template<typename T>
struct s {
    T typeholder;
    std::vector<T> list;
};

这很好用,使用:

typedef typename std::vector<decltype(x.typeholder)>::iterator IT;

我哪里错了?需要定义一个未使用的变量来保存类型似乎很复杂。我是不是在滥用::value_type?

【问题讨论】:

  • 在你的情况下:using IT = decltype(x.list.begin());.

标签: c++ gcc vector struct types


【解决方案1】:

decltype(x.list[0]) 的类型是long double&amp;。 std::vector 无法存储引用,因此会出现错误。第二个错误(“错误:'x' 的值不能在常量表达式中使用。”)似乎也很明显:你需要一个类型而不是一个值。这应该编译没有错误:

#include <vector>

template<typename T>
struct s {
    std::vector<T> list;
};

int main()
{
    s<long double> x;
    typedef typename std::vector<decltype(x.list)::value_type>::iterator IT;
}

【讨论】:

  • 让它成为引用类型而不是普通的long double的原因是什么?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多