Operator Overloading with class template
Eyyub
eyyub.pangearaion at gmail.com
Mon Apr 9 03:04:48 PDT 2012
On Monday, 9 April 2012 at 09:09:05 UTC, James Miller wrote:
> * Eyyub <eyyub.pangearaion at gmail.com> [2012-04-09 01:14:32
> +0200]:
>
>> Hello,
>>
>> How can I rewrite the exemple 2 (http://pastebin.com/q50903Zh)
>> in D
>> lang. ?
>> This source code doesn't work...why ?
>> http://paste.pocoo.org/show/wy1kDIpqTi2ApRuOxRRb/
>>
>> Thx. :)
>>
>
> What you want is something like this:
>
> class Value(int M, int K, int S)
> {
>
> private
> {
> float _value;
> }
>
> public
> {
> this(float val)
> {
> _value = val;
> }
>
> auto opBinary(string op : "/", int MO, int KO, int
> SO)(Value(MO, KO, SO) other) {
> return new Value!(M-MO, K-KO,
> S-SO)(_value/other.value);
> }
>
> }
> }
>
> A Few notes:
> 1. This isn't tested, might not work, but thats where you
> should aim...
> 2. Operator overloading is implemented as a lowering (as far as
> I'm aware) the
> compiler emits a template instantiation of opBinary("/") for
> the type. That
> means that you can add on more template arguments.
> 3. Using `auto` means that the compiler works out the type, so
> you don't have
> to add extra template arguments to calculate the correct
> type.
>
> Hope that helps.
>
> --
> James Miller
Ho, yeah it works !!! :D :D
http://paste.pocoo.org/show/ye7VXQHfLxsVM38bKyS6/
Thanks a lot !
More information about the Digitalmars-d-learn
mailing list