sizeof() on members

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

I am trying to migrate code to MSVS 2005. I found some code trying to take
sizeof a member in a nested struct, see below. I know the typedef is wacky,
probably a C coder who did not know C++ well. Now, to me, neither sizeof()
looks right, I thought there were restrictions on that kind of thing.
Apparently I can use the second variation, but that looks iffy to me as well.

Is the best(preferred?) way something like this?

S tempS; sizeof(tempS.x);

class C
{
typedef struct
{
int x;
} S;
void f()
{
sizeof(C::S::x); // Used to work
this->S::x; // Still works
}
};
 
Michael Bauers said:
I am trying to migrate code to MSVS 2005. I found some code trying to take
sizeof a member in a nested struct, see below. I know the typedef is
wacky,
probably a C coder who did not know C++ well. Now, to me, neither
sizeof()
looks right, I thought there were restrictions on that kind of thing.
Apparently I can use the second variation, but that looks iffy to me as
well.

Can you nuke the typedef, or at least put a tag on the nested struct so it's
not anonymous any longer. Then you can refer to it directly as before.
 
I shouldn't have even included the typedef, sorry. That just added confusion.

It's irrelevant, as the error occurs if I simply define S as this:
struct S
{
};
 
Michael said:
class C
{
typedef struct
{
int x;
} S;
void f()
{
sizeof(C::S::x); // Used to work

The compiler seems to be correct about this error, Comeau and the EDG
front-end fail with this code as well. Borland doesn't compile it
either. Just go to dinkumware.com or comeaucomputing.com and try to
compile it online.

The reason it fails is because x is a nonstatic member. You can't use
the S::x syntax there. Try this, it should work:

sizeof(static_cast<S*>(0)->x);

I'm not sure if it's possible to get this expression any simpler than this.
this->S::x; // Still works

This shouldn't compile either.

Tom
 
Back
Top