c++ - 我怎样才能得到一个vector::value_type的sizeof?

标签 c++ c++11 vector sizeof value-type

我想获取 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/

相关文章:

c++ - 带有标准容器的 unique_ptr : attempting to reference a deleted function

c++ - 重新哈希由列表 vector 组成的哈希表 C++

结构数组的 C++ 选择排序

c++ - 在 C++ 中访问程序外的变量

c++ - Wine 链接器错误 : trying to create . lnk

c++ - Qt - 创建一个基于时间的 UUID

c++ - 不同命名空间中别名声明的成员特化

c++ - 错误 : aggregate ‘food_type a’ has incomplete type and cannot be defined

r - 查找向量的哪个元素在 R 中的两个值之间

c++ - 如何用C++中的两个字符串 vector 创建一个字符串?