pfr
pfr copied to clipboard
Get structure padding
Is it possible to calculate structure padding using this library ?
Yes. sizeof(your_structure) - sizeof(all fields), iterate over the fields using this library.
Or do you mean alignment? Than just use alignof
I mean to have a predefined constexpr function in the library.
I'm still not shure what do you want to get. Please, provide a sample implementation of such function.
template<typename T>
void f(T&& value)
{
static constexpr size_t padding = get_padding<T>();
if constexpr (padding > 8){
Do this
}
else{
Do that
}
}
I need a more usable example to understand what are the use-cases and what API suits those cases best. For what do you need the padding and how are you planning to use it?
My intent was to automatically detect structure padding and use it for memory optimization if there is a padding.
For instance optional<MyStruct> doesn't need to waste additional 8 bytes for a single boolean.
I think you can use something like this
template<typename T>
consteval bool get_padding() {
namespace hana = boost::hana;
auto field_size = [](auto i) {
return sizeof(boost::pfr::get<i>(std::declval<T>()));
};
constexpr size_t count = boost::pfr::tuple_size_v<T>;
auto range = hana::make_range(hana::int_c<0>, hana::int_c<count>);
constexpr size_t result = hana::unpack(range, [=](auto... is) {
return (0 + ... + field_size(is));
});
return sizeof(T) - result;
}
@technic I see that I was not clear in the original request. This approach does calculates the padding but it doesn't say where the padding is. For instance given
struct A{
int a;
char b;
int c;
chat d;
int e;
};
The padding could be 6 bytes in the middle and 0 bytes in the end.
My original intent is to use this padding for internal purposes to reduce memory usage.
Thanks.