Operator Overloading with class template

James Miller james at aatch.net
Mon Apr 9 01:59:57 PDT 2012


* 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


More information about the Digitalmars-d-learn mailing list