如何为所有数字类型创建一个通用类? [英] How do I make a class generic for all Numeric Types?
问题描述
我正在尝试创建一个适用于所有数字类型的 Vector 类.我最初的尝试是为所有类型编写一个类,如下所示:
I am trying to create a Vector class that is generic for all numeric types. my original attempt was to write a class for all Types like this:
class Vector3f(val x:Float, val y:Float, val z:Float)
由于 scala 支持专门的注释,我可以使用它为所有数字类型生成这些类
since scala supports the specialised annotation I could use this to generate me these classes for all numeric types
class Vector3[A <: What?](val x:A,val y:A, val z:A)
但我发现的所有数字超类型都是 AnyVal,但 AnyVal 不支持 + - */.那么在不牺牲未装箱数字类型的性能的情况下,正确的方法是什么?
but everything I found as a super type for numbers was AnyVal, but AnyVal does not support + - * /. So what is the right way to do this, but without sacrificing the performance of unboxed number types?
推荐答案
你不能.不是现在.也许何时以及如果 Numeric
变得专业化.
You can't. Not right now. Maybe when, and if, Numeric
gets specialized.
假设你得到了最简单的参数化类:
Say you get the simplest parameterized class possible:
class Vector3[@specialized T](val x: T, val y: T, val z: T)(implicit num: Numeric[T]) {
def +(other: Vector3[T]) = new Vector3(num.plus(x, other.x), num.plus(y, other.y), num.plus(z, other.z))
}
+
方法会编译成大致如下:
The method +
will compile into something roughly like this:
override <specialized> def +$mcD$sp(other: Vector3): Vector3 = new Vector3$mcD$sp(
scala.Double.unbox(
Vector3$mcD$sp.this.Vector3$$num.plus(
scala.Double.box(Vector3$mcD$sp.this.x()),
scala.Double.box(other.x$mcD$sp()))),
scala.Double.unbox(
Vector3$mcD$sp.this.Vector3$$num.plus(
scala.Double.box(Vector3$mcD$sp.this.y()),
scala.Double.box(other.y$mcD$sp()))),
scala.Double.unbox(
Vector3$mcD$sp.this.Vector3$$num.plus(
scala.Double.box(Vector3$mcD$sp.this.z()),
scala.Double.box(other.z$mcD$sp()))),
Vector3$mcD$sp.this.Vector3$$num);
这是 scalac -optimize -Xprint:jvm
输出.现在每个特化类型甚至都有子类,这样你就可以在不装箱的情况下初始化一个Vector3
,但只要Numeric
不是特化的,你就不能走得更远.
That's scalac -optimize -Xprint:jvm
output. Now there are even subclasses for each specialized type, so that you can initialize a Vector3
without boxing, but as long as Numeric
is not specialized, you can't go further.
嗯...您可以编写自己的 Numeric
并对其进行专门化,但是,在这一点上,我不确定通过首先将类参数化来获得什么.
Well... you can write your own Numeric
and specialize that, but, at that point, I'm not sure what you are gaining by making the class parameterized in first place.
这篇关于如何为所有数字类型创建一个通用类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!