A template construct like using()
user1234
user1234 at 12.de
Wed Apr 27 14:45:55 UTC 2022
On Tuesday, 26 April 2022 at 21:33:43 UTC, Chris Katko wrote:
> I swear I asked something like this before years ago but it
> doesn't show up in my previous forum posts.
>
> I'm looking for a construct that mimics using(var)/with(var)
>
> ```D
> bitmap* b;
>
> draw_with(b)
> {
> draw_pixel(red, 16, 16); //draw red pixel to bitmap b (b is
> implied above)
> }
> ```
>
> But the code ends up being:
> ```D
> bitmap* b;
>
> set_target_bitmap(b); //entry code
> draw_pixel(red, 16, 16); // body
> set_target_bitmap(original_target); // exit code
> ```
>
> The essence is wrapping something the code up in a kind of
> RAII-like entry and exit code that references a given target
> variable.
>
> Perhaps a mixin is what I'm looking for?
assuming `set_target_bitmap` returns the previous target :
```d
struct Bitmap
{
}
struct PushPopBitmap
{
Bitmap* bitmap;
Bitmap* old;
alias bitmap this;
this(Bitmap* bmp) {
old = set_target_bitmap(bitmap = bmp);
}
~this() {
set_target_bitmap(old);
}
}
Bitmap* set_target_bitmap(Bitmap* bmp);
void draw_pixel();
void main()
{
Bitmap* bmp;
with (PushPopBitmap(bmp)) draw_pixel();
}
```
At the end of the WithStatement block that restores the previous
context.
More information about the Digitalmars-d-learn
mailing list