如何在 C++ 中获取尚未定义的结构体的 sizeof

Abd*_*nzi 5 c++ struct sizeof

struct S1
{
    size_t v = sizeof(S2); //compiler error here
};

struct S2
{
    S1 s1;
};
Run Code Online (Sandbox Code Playgroud)

struct S2 需要低于 S1,以便它可以将其作为成员,但我也希望 sizeof(S2) 存储在 S1 中。

我做了一个解决方法,我放置了一个返回 sizeof(S2) 但在定义 S2 之后定义的函数原型,如下所示:

size_t func();

struct S1
{
    size_t v = func();
};

struct S2
{
    S1 s1;
};

size_t func()
{
    return sizeof(S2);
}
Run Code Online (Sandbox Code Playgroud)

但我觉得这是一个非常丑陋和糟糕的解决方案,有更好的方法吗?

Erd*_*çük 10

由于是一个编译时运算符,因此将其声明为(常量)静态数据成员(不绑定到类实例)sizeof是有意义的,例如v

struct S1
{
    static const size_t v; //declare as static
};

struct S2
{
    S1 s1;
};

//then

const size_t S1::v = sizeof(S2); //define it after S2 is defined
Run Code Online (Sandbox Code Playgroud)

或作为全局变量

inline constexpr size_t S2_size = sizeof(S2); //often used as shortcut/alias
                                              //does not do much here
Run Code Online (Sandbox Code Playgroud)

根据以下评论:

struct S1
{
    size_t v;
    S1(size_t s) : v{s} {}
};

struct S2
{
    S1 s1;
    S2() : s1{sizeof(S2)} {}
};

struct S3
{
    S1 s1;
    S3() : s1{sizeof(S3)} {}
};

//...
Run Code Online (Sandbox Code Playgroud)


for*_*818 5

当您使用构造函数而不是类内初始值设定项时,问题就消失了:

struct S1
{
    size_t v;
    S1();
};

struct S2
{
    S1 s1;
};

S1::S1() : v(sizeof(S2)) {}
Run Code Online (Sandbox Code Playgroud)