4 ms·
Field inheritance is surprisingly natural in C, where a struct can be cast to it's first member.
by PhilipRoman 1y ago
Field inheritance is surprisingly natural in C, where a struct can be cast to it's first member.
- 1718627440 1y agoNote that you only need to cast for an upcast. To access the first member, you wouldn't need to cast. It would be nice though, if syntax like the following would be supported: struct A { int a; }; struct B { int b; struct A a; }; void foo (struct A * a) { struct B * b; &b->a = pa; } struct B b; foo (&b.a);
- PhilipRoman 1y agoYeah you're right, I meant the other way around. Also another loosely related idea is the container_of macro in Linux kernel.
- 1718627440 1y agoYeah, my idea is literally native type-safe support of container_of for assignment in the compiler.
- teo_zero 1y agoIn what scenario would this be useful? If foo() takes a struct A, it should be more generic and have no knowledge about the more specialized struct B.
- 1718627440 1y agoIn exact that same scenario, that you would cast to a subclass in another language, it's about language support for what for example the kernel does with container_of. Of course casting to a subclass isn't guaranteed to succeed always, but for example when you have actually declared it as the subclass elsewhere it's fine without checking for isinstance.