Why can't we derive struct's?

Walter Bright newshound2 at digitalmars.com
Fri Dec 21 03:04:13 UTC 2018


On 12/20/2018 12:15 AM, Manu wrote:
> Right, by necessity, because an empty struct member takes padded space
> in the aggregate.
> I think C++ gets the empty-base-class mechanic right; it doesn't take space.

It does take space in C++ depending on the compiler and the circumstance (it's 
rather complicated). D behaves like the associated C++ compiler in that regard - 
if it doesn't please file a bug report.

> I'm demonstrating crappy code that appears extremely frequently in lieu.
> Perhaps you have a better suggestion?
> 
>>> Why should it be impossible to derive a struct?
>>
>> Because polymorphism makes little sense for a value type.
> 
> It's not really polymorphism without a vtable, just simple extension.
> `alias this` produces the same result, it's just more wordy, kinda
> ugly, and boilerplate-ey.

It seems you have a workaround for what you want to do, and it's a simple paste 
job. You could probably accomplish the same thing with a mixin template.

> It also hogs the `alias this` slot.

C++ doesn't have alias this, so why would there be a slot for it?


>>   > static if (Base.tupleof.length == 0)
>>
>> static if (Base.sizeof == 0)
> 
> Empty struct has sizeof == 1 no? It certainly takes that many bytes as
> a member,

Not necessarily, see "empty base optimization". But you're right for this 
particular case.

https://en.wikibooks.org/wiki/More_C%2B%2B_Idioms/Empty_Base_Optimization


More information about the Digitalmars-d mailing list