[英]Type of Vector's Elements for Use in Iterator Type
If I have a struct s
: 如果我有一个结构
s
:
template<typename T>
struct s {
std::vector<T> list;
};
Defined in main()
as: 在
main()
定义为:
s<long double> x;
And I try to get the type of list
's iterator using: 我尝试使用以下方法获取
list
的迭代器类型:
typedef typename std::vector<decltype(x.list[0])>::iterator IT;
GCC 7.2.1 produces a bunch of errors, beginning with: 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*;
^
I doubt there is anything wrong with the underlying implementation of C++ in GCC, which this error seems to indicate. 我怀疑在GCC中C ++的基础实现是否存在错误,此错误似乎表明了这一点。
Using this method also assumes that list
is not empty, so I instead tried using ::value_type
(as suggested on other SO answers): 使用此方法还假定
list
不为空,因此我尝试使用::value_type
(如其他SO答案所建议):
typedef typename std::vector<x.list::value_type>::iterator IT;
GCC again produces errors: GCC再次产生错误:
error: the value of 'x' is not usable in a constant expression.
typedef typename std::vector<x.list::value_type>::iterator IT;
^~~~
In order to find an alternative, I added a type-holding variable to the struct: 为了找到替代方法,我向该结构添加了一个类型保持变量:
template<typename T>
struct s {
T typeholder;
std::vector<T> list;
};
And this worked fine, using: 使用以下方法可以正常工作:
typedef typename std::vector<decltype(x.typeholder)>::iterator IT;
Where am I going wrong here? 我在哪里错了? It seems convoluted to need to define an unused variable just to hold the type.
似乎很困惑,需要定义一个未使用的变量只是为了保存类型。 Am I misusing
::value_type
? 我在滥用
::value_type
吗?
The type of decltype(x.list[0])
is long double&
. decltype(x.list[0])
为long double&
。 std::vector
cannot store references, hence you get an error. std::vector
无法存储引用,因此会出现错误。 The second error ("error: the value of 'x' is not usable in a constant expression.") also seems pretty obvious: you need a type instead of a value. 第二个错误(“错误:'x'的值在常量表达式中不可用。”)看起来也很明显:您需要类型而不是值。 This should compile without errors:
这应该编译没有错误:
#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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.