how to get the size of the padding at the end of a class

倖福魔咒の 提交于 2019-12-08 03:02:26

I found a solution which seems to work on GCC and clang, at least for the example you gave.

namespace detail {

template <typename T, int N>
struct add_padding : add_padding<T, N - 1> {
    char pad;
};

template <typename T>
struct add_padding<T, 0> : T {
};

} // namespace detail

template <typename T, int N = 1, bool = (sizeof(T) == sizeof(detail::add_padding<T, N>))>
struct padding_size {
    static constexpr int value = padding_size<T, N + 1>::value;
};

template <typename T, int N>
struct padding_size<T, N, false> {
    static constexpr int value = N - 1;
};

It breaks for padding that is not caused by inheriting from different-sized types, and it doesn't work with MSVC at all. So it's not really an answer to your question I'm afraid, but maybe it helps someone else. Here's a live example.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!