java - How to do a template class (where the template extends Number) which use number addition? -


hello want simple thing. make template function numbers. want little ability "add". in c++ trivial this:

template <typename t> inline t add (t a, t  b) {      return + b;  }    int main(int argc, char** argv){    printf("int: %d\n",add(1,2));    printf("float: %f\n",add(1.1,2.1)); } 

in java got tough lesson. i'm new java believe (and hope) i'm totally wrong , on engineering this. thing come was:

public interface intrfcwownumbersadds<t> {     t add(number v); }  public class supersmartinteger extends number implements intrfcwownumbersadds<supersmartinteger>{     private integer i;     public supersmartinteger(int v) {         = v;     }      @override     public string tostring(){         return ""+i;     }      @override     public supersmartinteger add(number v) {         return new supersmartinteger(this.intvalue()+v.intvalue());     }      @override     public int intvalue() {         return i; // thx god auto(un)boxing     }      @override     public long longvalue() {         return i;     }      @override     public float floatvalue() {         return i;     }      @override     public double doublevalue() {         return i;     } } 

and note crazy wrapper above have number use template (eg double, byte etc...)

public class threadsafenum<t extends number & intrfcwownumbersadds<t>> {     private t    num;      public threadsafenum(t n){         num = n;     }      public t add(t v){         // note in here plan locking...         return num = num.add(v);     } } 

then can use as:

supersmartinteger = new supersmartinteger(5); supersmartinteger i2 = i.add(6); system.out.println(""+i2); threadsafenum<supersmartinteger> tsn = new threadsafenum<supersmartinteger>(i); supersmartinteger i3 = tsn.add(i2); 

i know when add() adding can use + operator , rely on auto(un)boxing. add() method meant (like lock).

so how properly? or way correct???

something base class:

public abstract class addable<t extends number,u extends addable<t,u>> {   private final t value;   public addable( final t value ){ this.value = value; }   public t getvalue(){ return value; }   public abstract u add( u addend ); } 

and sub-class:

public class addableinteger extends addable<integer,addableinteger> {   public addableinteger( final integer value ){     super( value );   }    @override   public addableinteger add( final addableinteger addend ){     java.util.objects.requirenonnull( addend );     return new addableinteger( this.getvalue() + addend.getvalue() );   } } 

Comments

Popular posts from this blog

c++ - Difference between pre and post decrement in recursive function argument -

php - Nothing but 'run(); ' when browsing to my local project, how do I fix this? -

php - How can I echo out this array? -