我很难从 C++/模板世界过渡到 scala。我习惯于对我想要的模板参数 T 使用任何操作,只要我用来实例化 T 的任何东西都支持这些操作(基本上是编译时 Duck 类型)。我在 Scala 中找不到相应的习惯用法,它允许我定义一个具有单个类型参数的抽象类,并且它需要类型 T 的某个接口。
我几乎可以工作,但我无法弄清楚如何告诉抽象类(Texture[T <: Summable[T]])T 支持从 Int 进行转换/构造。如何将隐式转换添加到特征 Summable 以便 Texture 知道 T 支持转换?
trait Summable[T] {
def += (v : T) : Unit
def -= (v : T) : Unit
}
object Int4 { implicit def int2Int4(i : Int) = new Int4(i, i, i, i) }
class Int4 (var x : Int, var y : Int, var z : Int, var w : Int) extends Summable[Int4] {
def this (v : Int) = this(v, v, v, v)
def += (v : Int4) : Unit = { x += v.x; y += v.y; z += v.z; w += v.w }
def -= (v : Int4) : Unit = { x -= v.x; y -= v.y; z -= v.z; w -= v.w }
}
abstract class Texture[Texel <: Summable[Texel]] {
var counter : Texel
def accumulate(v : Texel) : Unit = { counter += v }
def decrement() : Unit = { counter -= 1 } //< COMPILE ERROR HERE, fails to find implicit
}
class Int4Target extends Texture[Int4] {
var counter : Int4 = new Int4(0, 1, 2, 3)
}