templates and traits
Chris Katko
ckatko at gmail.com
Sat Mar 18 19:22:07 UTC 2023
Given:
```D
struct pos {float x, y;}
draw(myBitmap, pos(320, 240), centered);
draw(pos(320, 240), myBitmap);
draw("text", myFont, pos(320, 240));
```
I'm writing a general "draw" template function that through
compile-time, calls an associated DAllegro/Allegro 5 function:
```
draw(myBitmap, pos(320, 240), centered); //
al_draw_bitmap(myBitmap, pos.x - myBitmap.w/2, pos.y -
myBitmap.h, 0);
draw(pos(320, 240), myBitmap); // order doesn't matter
draw("text", myFont, pos(320, 240)); // different function
al_draw_text(...)
```
So there's multiple sub-problems to solve. I asked this years
ago, and got 90% of the way done and then lost the code and
cannot find the original forum post.
The pos(320,240) part works fine already. I need:
- At compile-time, for a variadic template that can take any
number of arguments, if specific arguments are available, I
branch and use them to call a specific applicable C function.
I remember I need to write some sort of enum function that checks
"IsAny" if an argument is passed at all, as well as one to find
where that argument is. Passing duplicates probably don't matter
(at least not right now), first valid argument is fine. I can't
seem to write code (or find example code online) that does this.
But it's something like
```D
enum isAny() = .......;
void draw(T...)(T)
{
if(isAny(bitmap))
{
// it's a sprite, now find out if we need it rotated,
stretched, etc.
}
is(isAny(string))
{
// its text [...]
}
}
```
A separate problem I've run into is, the 'centered' construct. If
I have rotate(25) (rotate 25 degrees), that works. But I cannot
just pass a type named "centered" with no variable attached to
it, nor can I--I think--pass an enum. I could do centered(false)
or centered(0), but that's clunkier than just saying "if
'centered' is an argument, we center it. If not, we don't." I
could have a variable named centered, I guess. or an enum with
{isCentered=1, notCentered=0} and detect if the enum is passed.
Lot's of ways to skin this cat.
The idea here, is I've got a lot of optional arguments (centered,
tinted, rotated, scaled, sheared, etc) that I can pick from and I
don't want to have to sort through a list of 80 different
permutations of function signatures, or, one gigantic
megafunction with a ton of zeros/nulls for all the unused
arguments.
This is a bit of a confusing problem to explain, so I've probably
left something necessary out.
More information about the Digitalmars-d-learn
mailing list