在 C++ 中,有什么方法可以优化组合的空类型而不是继承?

In C++ is there any way to optimize for empty types for composition as opposed to inheritance?

C++ 中的一个很酷的特性是空 base/type 优化,所以:

struct EmptyType {};

struct Foo : EmptyType
{
    long long a;
};

int main()
{
    sizeof(EmptyType); // Is 1
    sizeof(Foo::a); // Is 8
    sizeof(Foo); // Is not sizeof(a) + sizeof(EmptyType), is still 8
}

但是我想知道您是否可以针对在组合中使用空类型进行这种优化:

struct EmptyType {};

struct Foo : EmptyType
{
    long long a;
    EmptyType b;
};

int main()
{
    sizeof(EmptyType); // Is 1
    sizeof(Foo::a); // Is 8
    sizeof(Foo); /* Is 16, EmptyType still has to take up its size (ie., 1) in 
                 class Foo. Of course its aligned to 8 bytes*/
}

是否可以创建一个空类型,例如只有函数,以这种方式不占用 space?我原以为编译器可以轻松进行优化。

是的,从 C++20 开始,您可以使用 [[no_unique_address]] 属性:

#include <iostream>

struct empty {};

struct foo {
    [[no_unique_address]] empty b;
    int a;
};

int main() {
    foo x;
    std::cout << &x.b << '\n' << &x.a << '\n'; // may print the same address
    std::cout << sizeof(int) << ' ' << sizeof(x) << '\n'; // may be equal
}