【发布时间】:2019-07-29 02:34:47
【问题描述】:
我正在尝试创建一个以字节为单位返回参数包总大小的函数,但我无法找到解决方案!
template <typename... TTypes>
struct Test {
constexpr size_t getPackSizeInBytes() const {
// sizeof(TTypes) gives `unexpanded pack` error
}
};
// What I'm hoping for:
Test<uint8, uint16> test;
std::cout << test.getPackSizeInBytes() << std::endl;
// Should output 3;
感谢您的帮助!
【问题讨论】:
-
@songyuanyao 你为什么删除你的答案?
-
@MartinYork 我认为 OP 想在每种类型上调用
sizeof并获取摘要。 -
当您说
// Should output 3;时,您的意思是应该是sizeof(uint8) + sizeof(uint16)。我不想假设非标准类型的大小。虽然std::uint8_t和std::uint16_t应该是 24 位。但这并不意味着一个字节是 8 位。你需要检查CHAR_BITS。 -
请注意,计算类型的各个大小的总和通常不会产生与将相同类型封装为成员的结构相同的值。对齐要求通常意味着这样的结构比其单个组件更大。