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

anonymous via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Mon Jan 25 07:57:06 PST 2016


On 25.01.2016 15:51, pineapple wrote:
> 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 =

Can't have variables like that in templates. Make it a "manifest 
constant" with  enum. Also, if you want opmethod!("foo", "bar") to 
evaluate to the code, then methodtemplate needs to be renamed to 
"opmethod". I.e., make this line:
----
enum opmethod =
----

Also, opmethod doesn't need to be template. A function would work as well:
----
     static string opmethod(string methoddef, string methodcall)
     {
         return
             "unitvalue " ~ methoddef ~ "{
                 unitvalue copy = this.copy();
                 copy." ~ methodcall ~ ";
                 return copy;
             }"
         ;
     }

     mixin(unitvalue.opmethod(
         "sum(in unitvalue value)", "add(value)"
     ));
----

>              "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;

This gives me an error, too: "Error: incompatible types for 
((this.exponents) == (value.exponents)): 'int[int]' and 'const(int[int])'"

(I've aliased unit to int.)

As far as I can tell, this should work. There's a bugzilla issue for it:
https://issues.dlang.org/show_bug.cgi?id=13622

You can work around the bogus error message by using a const temporary 
for this.exponent:
----
         const this_exponents = this.exponents;
         return this_exponents == value.exponents;
----

>      }
> }
>



More information about the Digitalmars-d-learn mailing list