【发布时间】:2020-08-21 08:52:34
【问题描述】:
我有一个与question 类似的问题。 我想在编译时获取结构的大小,包括所有没有添加编译器特定填充的子结构。
struct Bar {
BOOST_HANA_DEFINE_STRUCT(Bar,
(std::uint8_t, a),
(std::uint16_t, b)
);
};
struct Foo {
BOOST_HANA_DEFINE_STRUCT(Foo,
(std::uint8_t, a),
(std::uint16_t, b),
(std::uint32_t, c),
(std::uint64_t, d),
(Bar, bar)
);
};
template <typename T>
constexpr auto bytesize() -> size_t
{
if constexpr (std::is_arithmetic<T>::value || std::is_enum<T>::value)
return sizeof(T);
else if constexpr (std::is_class<T>::value)
{
return hana::fold_left(
hana::accessors<T>(), 0, [](auto total, auto member) {
// I want to call bytesize recusively here:
return bytesize<decltype(hana::second(member)(std::declval<T>()))>() + total;
});
}
}
static_assert(bytesize<Foo>() == 18);
由于我不想包含填充,我希望结构 Foo 的大小为 18(包括子结构 Bar 的大小),但链接问题中的代码确实包含填充计算并给我一个 19 的大小。问题在于函数应该在它遇到的所有结构上递归调用字节大小。
可以在here 找到一个无法按预期工作的最小示例。
【问题讨论】:
-
您的最小示例与获取结构的大小无关。它是关于断言一个特定的大小。
-
@idclev463035818 检查函数
bytesize中注释掉的部分,这是不起作用的部分 -
没有bytesize函数,请在问题中附上代码
-
您期望的结果是什么?你得到什么输出?请花一些时间来the help pages,接受SO tour,阅读How to Ask,以及this question checklist。
标签: c++ c++17 boost-hana