Operator overloading

Xan xancorreu at gmail.com
Thu Apr 19 12:31:42 PDT 2012


On Thursday, 19 April 2012 at 19:24:40 UTC, Dmitry Olshansky 
wrote:
> On 19.04.2012 23:14, 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) {
> Algorisme! opBinary(string op) (Algorisme alg) {
>
> or
> Algorisme!(U,V) opBinary(string op) (Algorisme!(U,V) alg) {
>
> should do it
>
> static if (op == '*') return new Algorisme("composició",
>
> or:
> static if (op == '*') return new Algorisme!(U,v)("composició",
>
> same here. There is no need to put !(params) explicitly if it's 
> the same as the template you are writing.
>
>> this.versio+alg.versio, this.funcio);
>> }
>>


Thanks, Dmitry, but it's a correction "*" instead of '*' (string 
instead of char)

The definitive code is:

	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);
	}


Thanks a lot, another time,
Xan.


>> }
>> [...]
>>
>> 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?
>>
>> Thanks,
>> Xan.




More information about the Digitalmars-d-learn mailing list