Why doesn't sizeof parse struct members?

Viewed 2937

I know that sizeof is a compile-time calculation, but this seems odd to me: The compiler can take either a type name, or an expression (from which it deduces the type). But how do you identify a type within a class? It seems the only way is to pass an expression, which seems pretty clunky.

struct X { int x; };
int main() {
    // return sizeof(X::x); // doesn't work
    return sizeof(X()::x); // works, and requires X to be default-constructible
}
3 Answers

An alternate method works without needing a default constructor:

return sizeof(((X *)0)->x);

You can wrap this in a macro so it reads better:

#define member_sizeof(T,F) sizeof(((T *)0)->F)

Here is a solution without the nasty null pointer dereferencing ;)

struct X { int x; };

template<class T> T make(); // note it's only a declaration

int main()
{
    std::cout << sizeof(make<X>().x) << std::endl;
}

What about offsetof? Have a look here. Also have a look here, which combines both sizeof and offsetof into a macro.

Hope this helps.

Related