我可以在不创建结构体实例的情况下获取结构体字段的大小吗?
如果您有结构体的实例,那么在 C++ 中获取结构体字段的大小是很简单的。例如(未编译):
typedef struct Foo {
int bar;
bool baz;
} Foo;
// ...
Foo s;
StoreInSomething(s.bar, sizeof(s.bar)); // easy as pie
现在我仍然可以做这样的事情,但是使用我正在实现的接口(我得到一个 BOOL 指示位字段中特定位的状态应该是什么),我将创建结构体只是为了获取数据成员的大小。有没有办法向编译器指示它应该使用结构体字段的大小而不创建该结构体的实例?这在哲学上相当于:
SetBit(bool val) {
StoreInSomething(
BITFIELD_POSITION_CONSTANT, // position of bit being set
val, // true = 1, false = 0
sizeof(Foo::bar)); // This is, of course, illegal. (The method I've been told I must use req's the size of the target field.)
}
在堆栈上创建结构应该是快速且便宜的,但我怀疑我会在代码审查中为此感到沮丧,所以我正在寻找一种更好的方法,不会引入添加维护负担(例如尺寸的#defines)。
It's trivial to get the size of a struct's field in C++ if you have an instance of the struct. E.g. (uncompiled):
typedef struct Foo {
int bar;
bool baz;
} Foo;
// ...
Foo s;
StoreInSomething(s.bar, sizeof(s.bar)); // easy as pie
Now I can still do something like this, but with the interface I'm implementing (I get a BOOL that indicates what the state of a specific bit in a bitfield should be), I'd be creating the struct solely to get the size of the data member. Is there a way to indicate to the compiler that it should use the size of a struct's field without creating an instance of the struct? It would be the philosophical equivalent of:
SetBit(bool val) {
StoreInSomething(
BITFIELD_POSITION_CONSTANT, // position of bit being set
val, // true = 1, false = 0
sizeof(Foo::bar)); // This is, of course, illegal. (The method I've been told I must use req's the size of the target field.)
}
Creating the struct on the stack should be fast and cheap, but I suspect I'll get dinged for it in a code review, so I'm looking for a better way that doesn't introduce an add'l maintenance burden (such as #defines for sizes).
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以使用如下表达式:
由于不计算
sizeof
的参数,仅计算其类型,因此实际上不会创建临时值。如果
Foo
不可默认构造(与您的示例不同),您必须使用不同的表达式,例如涉及指针的表达式。 (感谢迈克·西摩)You can use an expression such as:
As the argument of
sizeof
isn't evaluated, only its type, no temporary is actually created.If
Foo
wasn't default constructible (unlike your example), you'd have to use a different expression such as one involving a pointer. (Thanks to Mike Seymour)...
...
您可以将 sizeof 与指向结构的指针一起使用。考虑如下所示:
给出的结果如下:
You can use sizeof of with a pointer to the structure. Consider something like the following:
Which gives results such as: