There's no way to do this how you would in C++, sorry. Generics in Java work quite differently to C++ templates. In Java, only one version of the generic code is ever generated, and it has to be suitable for all type arguments. Because all the primitives have different representations in byte code, they can't share the same generic code. This is why only reference types are valid type arguments in Java.
I think the closest you could get would be to use the Number
class. Autoboxing will automatically convert any primitive numeric value into a subclass of Number
. E.g:
class Foo<T extends Number> {
public void operate(T number) {
double value = number.doubleValue();
// do something with the double
}
}
Foo<Integer> intFoo = new Foo<Integer>();
intFoo.operate(666);
intFoo.operate(666.0); // fails to compile
But the type parameter isn't really buying you much. And if you want the operate
method to return a value of type T, you have to resort to runtime checks, which kind of defeats the purpose.
A possibly interesting side note: Scala 2.8 will support an annotation @specialize
that basically tells the compiler "handle the type arguments the C++ way", and generates a different version of the code for each different type argument representation.