正确的类层次结构的二维和三维矢量 [英] proper class hierarchy for 2D and 3D vectors
问题描述
我想有一个大致的矢量抽象类/特征,指定某些方法,例如:
I want to have a general vector abstract class / trait that specifies certain methods, e.g.:
trait Vec
{
def +(v:Vec):Vec
def *(d:Double):Vec
def dot(v:Vec):Double
def norm:Double
}
我想有 Vec2D
和 Vec3D
延长 VEC
:
class Vec2D extends Vec { /* implementation */ }
class Vec3D extends Vec { /* implementation */ }
但我怎么能,例如,让这个 Vec2D
只能添加到其他 Vec2D
和不要 Vec3D
?
But how can I, for instance, make it so that Vec2D
can only be added to other Vec2D
and not to Vec3D
?
现在我只是执行 Vec2D
和 Vec3D
没有共同 VEC
的祖先,但越来越重复的code乏味。我要实现依赖于这些类所有的几何类(如三角
,多边形
,网
,...)两次,一次为 Vec2D
,并再次 Vec3D
。
Right now I'm just implementing Vec2D
and Vec3D
without a common Vec
ancestor, but this is getting tedious with duplicate code. I have to implement all my geometry classes that depend on these classes (e.g. Triangle
, Polygon
, Mesh
, ...) twice, once for Vec2D
and again for Vec3D
.
我看到了Java实现: javax.vecmath.Vector2d
和 javax.vecmath.Vector3d
没有共同的祖先。什么是这个原因?有没有一种方法来克服它在Scala呢?
I see the java implementations: javax.vecmath.Vector2d
and javax.vecmath.Vector3d
do not have a common ancestor. What's the reason for this? Is there a way to overcome it in scala?
推荐答案
作为<一个href=\"http://stackoverflow.com/questions/4776864/scala-self-type-value-is-not-a-member-error/4777195#4777195\">requested,设计基性状的最有用的方法包括两个<一href=\"http://stackoverflow.com/questions/4773611/proper-class-hierarchy-for-2d-and-3d-vectors/4773642#4773642\">CRTP 和的的<一个href=\"http://stackoverflow.com/questions/4773611/proper-class-hierarchy-for-2d-and-3d-vectors/4773855#4773855\">self-type注释。
As requested, the most useful way of designing the base trait involves both the CRTP and the self-type annotation.
trait Vec[T <: Vec[T]] { this: T =>
def -(v: T): T
def *(d: Double): T
def dot(v: T): Double
def norm: Double = math.sqrt(this dot this)
def dist(v: T) = (this - v).norm
}
如果没有自我型,这是不可能叫 this.dot(本)
为点
预期一个 T
;因此,我们需要用注释来强制执行。
Without the self-type, it is not possible to call this.dot(this)
as dot
expects a T
; therefore we need to enforce it with the annotation.
在另一方面,没有CRTP,我们就不能叫规范
在(本 - V)
为 -
返回 T
,因此,我们需要确保我们的键入 T
有这种方法,例如声明 T
的是的 VEC [T]
。
On the other hand, without CRTP, we’ll fail to call norm
on (this - v)
as -
returns a T
and thus we need to make sure that our type T
has this method, e.g. declare that T
is a Vec[T]
.
这篇关于正确的类层次结构的二维和三维矢量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!