Operator overloading

Jonathan M Davis jmdavisProg at gmx.com
Thu Apr 19 13:58:52 PDT 2012


On Thursday, April 19, 2012 21:14:43 Xan wrote:
> Hi, I read http://dlang.org/operatoroverloading.html but in my
> code it does not work. I tried to overload '*' binary operator in
> my class Algorisme:
> 
> [...]
> class Algorisme(U,V) {
> string nom;
> uint versio;
> alias V function (U) Funcio;
> Funcio funcio;
> 
> this(string nom, uint versio, Funcio funcio) {
> try {
> this.nom = nom;
> this.versio = versio;
> this.funcio = funcio;
> }
> catch {
> writeln("Error");
> }
> }
> 
> string toString() {
> return format("%s (versió %s): %s -> %s", nom, versio,
> typeid(U), typeid(V));
> }
> 
> Algorisme(U, V) opBinary(string op) (Algorisme(U, V) alg) {
> static if (op == '*') return new Algorisme(U,V)("composició",
> this.versio+alg.versio, this.funcio);
> }
> 
> }
> [...]
> 
> but I receive these errors:
> 
> $ gdmd-4.6 algorisme.d
> algorisme.d:31: function declaration without return type. (Note
> that constructors are always named 'this')
> algorisme.d:31: no identifier for declarator Algorisme(U, V)
> algorisme.d:31: semicolon expected following function declaration
> algorisme.d:31: function declaration without return type. (Note
> that constructors are always named 'this')
> algorisme.d:31: function declaration without return type. (Note
> that constructors are always named 'this')
> algorisme.d:31: found 'alg' when expecting ')'
> algorisme.d:31: no identifier for declarator
> opBinary(Algorisme(U, V))
> algorisme.d:31: semicolon expected following function declaration
> algorisme.d:31: Declaration expected, not ')'
> algorisme.d:35: unrecognized declaration
> 
> 
> Why it fails?
> Anyone could help me?

Use a template constraint rather than a static if. As it stands, any operator 
other than "*" will result in a function with no return statement.

Algorisme opBinary(string op)(Algorisme alg)
 if(op == "*")
{
 return new Algorisme("composició", this.versio+alg.versio, this.funcio);
}

- Jonathan M Davis


More information about the Digitalmars-d-learn mailing list