Error using templates: "cannot use template to add field to aggregate '<class>'"

pineapple via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Mon Jan 25 06:51:21 PST 2016


I'm getting several of these since I'm trying to do the same 
thing in a few places. Here's a complete error:

     path\to\file.d(55): Error: variable 
units.unitvalue.opmethod!("sum(in unitvalue value)", 
"add(value)").methodtemplate cannot use template to add field to 
aggregate 'unitvalue'
     path\to\file.d(127): Error: template instance 
units.unitvalue.opmethod!("sum(in unitvalue value)", 
"add(value)") error instantiating

In this class I wrote a number of methods like "multiply", 
"divide", "add", "subtract" and I want to add alternatives that 
don't modify the object. In this particular instance, I'm trying 
to wrap the "add" method in another named "sum" that doesn't 
modify the original object, simply by making a copy first and 
operating upon that instead.

What am I doing wrong?

The relevant bits of my class look like this:

class unitvalue{
     double coefficient;
     int[unit] exponents;

     unitvalue copy(){
         unitvalue value = new unitvalue();
         value.coefficient = this.coefficient;
         value.exponents = this.exponents.dup;
         return value;
     }

     template opmethod(string methoddef, string methodcall){
         const char[] methodtemplate =
             "unitvalue " ~ methoddef ~ "{
                 unitvalue copy = this.copy();
                 copy." ~ methodcall ~ ";
                 return copy;
             }"
         ;
     }

     mixin(unitvalue.opmethod!(
         "sum(in unitvalue value)", "add(value)"
     ));
     void add(in unitvalue value){
         if(!this.samedimensions(value)){
             throw new Exception("Cannot add values of differing 
dimensions.");
         }else{
             this.coefficient += value.coefficient;
         }
     }

     bool samedimensions(in unitvalue value){
         return this.exponents == value.exponents;
     }
}



More information about the Digitalmars-d-learn mailing list