I'm trying to use Boost MPL and Fusion to calculate the size of a struct exclusive of any padding. This is my current best attempt:
template<class T>
constexpr std::size_t sizeof_members(void)
{
using namespace std;
namespace mpl = boost::mpl;
namespace fusion = boost::fusion;
//This works, but only for structs containing exactly 4 members...
typedef typename mpl::apply<mpl::unpack_args<mpl::vector<mpl::_1, mpl::_2, mpl::_3, mpl::_4>::type >, T>::type member_types;
typedef typename mpl::transform<member_types, mpl::sizeof_<mpl::_1> >::type member_sizes;
typedef typename mpl::accumulate<member_sizes, mpl::int_<0>, mpl::plus<mpl::_1, mpl::_2> >::type sum;
return sum();
}
BOOST_FUSION_DEFINE_STRUCT(
(), Foo_t,
(std::uint8_t, a)
(std::uint16_t, b)
(std::uint32_t, c)
(std::uint64_t, d)
);
static_assert(sizeof_members<struct Foo_t>() == 15);
int main()
{
std::cout << "sizeof_members = " << sizeof_members<struct Foo_t>() << std::endl;
std::cout << "sizeof = " << sizeof(struct Foo_t) << std::endl;
return 0;
}
Expected output:
sizeof_members<struct Foo_t>() = 15
sizeof(struct Foo_t) = 16
I can transform a Sequence of types to a Sequence of integers containing the size of each type, and I can compute the sum over that Sequence, but I'm having trouble with the first step of turning the struct into a Sequence of types. The Fusion docs say that BOOST_FUSION_DEFINE_STRUCT generates boilerplate to define and adapt an arbitrary struct as a model of Random Access Sequence, which I believe should be compatible with mpl::transform, however there seems to be some glue code that I'm missing to make this work. My current approach using mpl::unpack_args works but only for structs with exactly four fields.
How can I extend this to arbitrary structs with more or fewer fields?