Non-virtual private struct inheritance

bearophile bearophileHUGS at lycos.com
Thu Aug 23 06:17:22 PDT 2012


monarch_dodra:

> In C++, it is a very common practice, when writing a struct 
> template, to have said template derive from a base non-template 
> struct. This makes sure there is no executable bloat,

"alias this" seems to help both for composition and against 
template bloat:


struct Foo {
     int x;
     int bar() { return x * 2; }
}
struct Bar(T) {
     Foo f;
     T y;
     alias f this;
}
void main() {
     Bar!int b1;
     b1.x = 10;
     assert(b1.bar() == 20);
     Bar!double b2;
     b2.x = 100;
     assert(b2.bar() == 200);
}


In the asm listing there is only one bar:

_D3foo3Foo3barMFZi:
     enter 4, 0
     mov EAX, [EAX]
     add EAX, EAX
     leave
     ret


Another way to fight template bloat is the @templated() I have 
suggested elsewhere, that applied to something inside a template 
allows you to choose what that something is templated to (even 
nothing).

Bye,
bearophile


More information about the Digitalmars-d mailing list