More Elegant Settable Methods?
jwatson-CO-edu
real.name at colorado.edu
Tue Jan 31 16:25:18 UTC 2023
On Monday, 30 January 2023 at 07:48:09 UTC, Salih Dincer wrote:
> On Saturday, 21 January 2023 at 23:07:45 UTC, jwatson-CO-edu
> wrote:
>> I am trying to create a struct with a settable method that has
>> access to the struct scope.
>> Is this the only way?
>> Is there a way to give access without explicitly passing
>> `this`?
>
> Why not use the delegate? What exactly do you want to do? Set
> after constructor or assign delegate?
>
> ```d
> struct S {
> float /*------------------*/ a;
> float /*------------------*/ b;
>
> void delegate(float x, float y) set;
> auto sum() { return a + b; }
> }
>
> void main() {
> S s;
> s.set = (x, y) {
> s.a = x;
> s.b = y;
> };
> s.set(10, 20);
> assert(s.sum == 30);
> }
> ```
>
> SDB at 79
So `delegate` looks closer to what I want. I am looking to
implement a [Strategy
Pattern](https://en.wikipedia.org/wiki/Strategy_pattern) in which
I have an object with an update method which is settable at
runtime, either during instantiation or after. The function you
have assigned to `set` has access to the `S` object, just like I
had wished; Thank you!
The application is a [Braitenberg
Vehicle](https://en.wikipedia.org/wiki/Braitenberg_vehicle)
environment. There are a more than a few component types that
are connected to each other in the same way and pass messages of
a consistent type. I'd like not to write a struct/class for each
component type; but rather write their common structure once and
set their type-specific behavior as they are created.
It looks like I can write a function for each component type and
assign a `delegate` update strategy after the common struct has
been created. This is what I had asked for. Thank you for this
lesson.
More information about the Digitalmars-d-learn
mailing list