是否有可能在特定的附加的结构,它的派生类的偏移在C + +?

问题描述 投票:3回答:2

只是想询问是否有可能在特定附加一个struct偏移,在其派生类?

例如 -

struct A
{
    int a;
    char b;
};

struct B : A
{
    int c; // place this before b?
};
c++ c++11
2个回答
1
投票

这是不可能没有遗憾的是改变A结构。您可以通过使A结构更加个性实现这一点:

template<typename T = void>
struct A {
    int a;
    T c;
    char b;
};

template<>
struct A<void> {
    int a;
    char b;
};

//           v------ Adds the int as the C member
struct B : A<int> {};

//           v----- Add no member
struct C : A<> {};

3
投票

不,你不能回避一个编译器需要订购会员的方式。

但是你可以立足于解决方案

template<typename A> struct B
{
    int c;
    A a;
};

你可以实例化一个实例说

B<A> foo;

即使是这样,虽然,有可能是ca之间填充。

© www.soinside.com 2019 - 2024. All rights reserved.