如何在 C++ 中获取类型的大小?

Mar*_*c-O 7 c++ clang oclint

我正在寻找一个返回类型大小的 C++ 函数。例如 :

#include <stdint.h> 

int16_t my_var; 
int32_t size_of_var; 

// magical_function is what I'm looking for
// size_of_var should be equal to 16 because my_var is a int16_t
size_of_var = my_var.magical_function() ; 
Run Code Online (Sandbox Code Playgroud)

我知道 size() 的存在是为了获取字符串的长度,所以我猜也有一个函数表明了这一点。

此外,我正在使用 Clang 库,所以我可以获得一个类型(http://clang.llvm.org/doxygen/classclang_1_1Type.html),但我目前不知道比较 2 种类型并了解它们之间的较大值二。

Bry*_*hen 8

如果你想要 16 而不是 2 int16_t

sizeof(my_var) * CHAR_BIT
Run Code Online (Sandbox Code Playgroud)

sizeof给你多少字节,CHAR_BIT给你一个字节有多少位(通常为 8)

  • @Zsolt 您说这有点令人困惑,但有时可能会令人困惑两下。 (3认同)

Pab*_*ark 6

命令 (sizeof) 的可用语法是:

  • 大小(类型)
  • 表达式的大小

他们俩都回来了std::size_t

类型的示例是int, float, double,而表达式可以评估对象的大小。为了澄清起见,我将添加以下内容:

sizeof(int);     // Return size of int type.
sizeof(float);   // Return size of float type.
sizeof(double);  // Return size of double type.

struct my_struct {};  // Creates an empty struct named my_struct.
my_struct alpha;      // Initializes alpha as a my_struct.
sizeof alpha;         // Returns size of alpha.
Run Code Online (Sandbox Code Playgroud)

可在此处找到更多信息。

希望能帮助到你!