On Thursday, 23 August 2012 at 13:17:23 UTC, bearophile wrote:
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
Thanks for the answer. Very nice. "alias this" is still the first
thing I think about, but in this case, it works perfectly well
actually.