Possible to overload assignment of struct field ??
Greetings, With a struct, there are many overload possibilities available. However, I haven't been able to find how to overload assignment of **selected fields** of a struct. For example, suppose: struct Foo{ int a; int b; ... } void main(){ auto x = Foo( 1, 2); // so x now instantiates x.a = 100; // suppose I wish to enforce that a<5?? ... } (I understand this is basically a field "setter" idea that is most often associated with classes. So, another way to state the quesion might be: "How can a field setter be done on a **already instantiated** struct?) Best Regards, James
Re: Possible to overload assignment of struct field ??
On 8/23/21 10:25 PM, james.p.leblanc wrote: So, you need a "property". Easy... :) 1) Rename the member e.g. as a_. 2) Write setter and getter functions named 'a'. struct Foo{ int a_; int a() const { return a_; } void a(int value) { a_ = value; } } void main(){ auto x = Foo(1); x.a = 100; assert(x.a == 100); } Ali
Re: Possible to overload assignment of struct field ??
On Tuesday, 24 August 2021 at 05:34:08 UTC, Ali Çehreli wrote: On 8/23/21 10:25 PM, james.p.leblanc wrote: So, you need a "property". Easy... :) 1) Rename the member e.g. as a_. 2) Write setter and getter functions named 'a'. struct Foo{ int a_; int a() const { return a_; } void a(int value) { a_ = value; } } void main(){ auto x = Foo(1); x.a = 100; assert(x.a == 100); } Ali Ali, Thank you ... yes! This is exactly what I needed, I have done something similar as you have shown for the "getter", but had a "brain-lock-up" when thinking about the setter. A bit embarassing for my, I admit. But, on the positive side ... the solution is now burned into my brain. Thanks again and Kind Regards, James