0
[✅SOLVED✅] C++ like function templates in Java?
Is there a way to use templates (like in C++) for making functions in Java? To explain what I mean better, is there something like: template <class T> T sum(T a, T b) { return a + b; } in Java?
2 odpowiedzi
+ 3
Note that templates and generic are not the same and behave differently, but they are probably the closest thing to what you're looking for. Java Generics will not work with primitive types. Instead you'll need to use their wrapper classes to box them as a generic type must inherit from the Object class.
The below generic method will behave similar to the template you posted.
public class Program
{
public static <T extends Number> T sum(T a, T b) {
if(a != null && b != null) {
if(a instanceof Byte) {
return (T) new Byte((byte)(a.byteValue() + b.byteValue()));
} else if(a instanceof Integer) {
return (T) new Integer(a.intValue() + b.intValue());
} else if(a instanceof Double) {
return (T) new Double(a.doubleValue() + b.doubleValue());
} else if(a instanceof Float) {
return (T) new Float(a.floatValue() + b.floatValue());
} // add checks for more types
}
return null;
}
public static void main(String[] args) {
System.out.println(sum(new Byte((byte)4), new Byte((byte)3)));
System.out.println(sum(new Integer(4), new Integer(4)));
System.out.println(sum(new Double(4.5), new Double(3.9)));
System.out.println(sum(new Float(4.2f), new Float(3.5f)));
}
}
0
These generic methods don't seem to be the most efficient things in the world, but at least they're better than having 50 function definitions. Thanks all! :D