如何使所有数字类型的类通用? [英] How do I make a class generic for all Numeric Types?

查看:110
本文介绍了如何使所有数字类型的类通用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个对所有数字类型通用的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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆