More than one invariant per struct/class

simendsjo simendsjo at gmail.com
Thu Aug 4 03:40:48 PDT 2011


On 04.08.2011 12:30, Pelle wrote:
> On Thu, 04 Aug 2011 11:32:03 +0200, simendsjo <simendsjo at gmail.com> wrote:
>
>> I would like to use a template mixin to add some fields to a struct,
>> but I'd also like the template to add additional invariant checks
>> without having to remember to add this for all struct/classes that
>> mixes in this code.
>>
>> class C {
>> int a;
>> }
>>
>> mixin template EmbedC() {
>> C _c;
>>
>> // oops.. more than one invariant
>> invariant() {
>> assert(_c);
>> }
>>
>> void close() {
>> _c = null;
>> }
>> }
>>
>> struct S {
>> int i = 10;
>> invariant() {
>> assert(i >= 10);
>> }
>>
>> mixin EmbedC!();
>> }
>>
>> void main() {
>> S s;
>> s.close();
>> s._c.a = 10; // access violation, but I want assertion from invariant
>> }
>
> What happens if you replace assert(_c) with assert(_c !is null)?

The problem is that you cannot include more than one invariant() in a 
struct or class.

struct S {
     invariant() {}
     invariant() {} // blows up
}

void main() {}

I could easily change the design for my use case, but I don't see why 
this restriction exists. Perhaps some more experienced users can comment 
on this.


More information about the Digitalmars-d-learn mailing list