我想获取 vector 中包含的类型的 sizeof
。这是我尝试过的:
#include <iostream>
#include <vector>
int main()
{
std::vector<uint> vecs;
std::cout << sizeof(vecs.value_type) << std::endl;
return 0;
}
据我了解,这应该是正确的。但是,当使用 GCC 4.8.1 编译时,我得到的是:
test-sizeof.cpp: In function ‘int main()’: test-sizeof.cpp:7:27: error: invalid use of ‘std::vector<unsigned int>::value_type’ std::cout << sizeof(vecs.value_type) << std::endl; ^
我做错了什么?如何获取包含类型的大小?
最佳答案
3.4.3 限定名称查找 [basic.lookup.qual]
1 The name of a class or namespace member or enumerator can be referred to after the :: scope resolution operator (5.1) applied to a nested-name-specifier that denotes its class, namespace, or enumeration. If a :: scope resolution operator in a nested-name-specifier is not preceded by a decltype-specifier, lookup of the name preceding that :: considers only namespaces, types, and templates whose specializations are types. If the name found does not designate a namespace or a class, enumeration, or dependent type, the program is ill-formed.
在这种情况下,您访问的是 type
来自类模板特化的成员 std::vector<uint>
,你需要通过写来做到这一点:
std::vector<uint>::value_type
如果您实际上在模板代码中并且想要例如访问相同的嵌套类型,您需要在它前面加上关键字 typename
像这样:
typename std::vector<T>::value_type
在 C++11 中,您可以使用 sizeof(decltype(vecs)::value_type)
或sizeof(decltype(vecs.back()))
, 如果您不知道类型的确切名称但知道如何通过成员函数(如 back()
)访问它们,则后者很方便。 .
注意:正如@Casey 在评论中指出的那样,decltype
需要剥离引用以获取类型本身,但对于 sizeof 的目的并不重要。
关于c++ - 我怎样才能得到一个vector::value_type的sizeof?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21290875/