如何在课程结束时获得填充的大小 [英] how to get the size of the padding at the end of a class

查看:76
本文介绍了如何在课程结束时获得填充的大小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样的A类:

struct V {
    virtual void f() = 0;
};

struct A {
    int data;
};

struct B : public A , public V {
    void f() override {}
};

MSVC在64位版本上为我提供了sizeof(A) == 4sizeof(B) == 16而不是12(sizeof(void*) + sizeof(A))-因此有4字节的填充.有没有办法得到填充?也许有一些特征?

MSVC gives me sizeof(A) == 4 and sizeof(B) == 16 on a 64 bit build instead of 12 (sizeof(void*) + sizeof(A)) - so there is a 4 byte padding. Is there a way to get that padding? perhaps with some trait?

我需要这样做的原因是要做这样的断言:

The reason I need this is to do an assert like this:

static_assert(sizeof(B) == sizeof(A) + std::is_polymorphic<camera>::value * sizeof(void*));

这意味着我想确保所有数据都在基类中,但是B应该能够通过从某个接口继承而成为多态的...不应将任何新成员添加到B中,但应该允许它是多态的.如果我在A中有2个整数,那么B ...

Meaning that I want to ensure that all data is in the base class, but B should be able to be polymorphic by inheriting from some interface... No new members shall be added to B but it should be allowed to be polymorphic. If I had 2 integers in A there would be 0 padding at the end of B...

推荐答案

我发现了一个似乎可以在GCC和clang上运行的解决方案,至少对于您给出的示例来说如此.

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;
};

它中断填充不是由从不同大小的类型继承引起的,并且根本不适用于MSVC.因此,恐怕这并不是您所提问题的真正答案,但也许可以帮助其他人.这是一个实时示例.

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.

这篇关于如何在课程结束时获得填充的大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆