加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

scala是否提供C模板之类的东西?

发布时间:2020-12-16 19:11:10 所属栏目:安全 来源:网络整理
导读:我来自C并试图绕着 scala的类型系统. 考虑以下C模板类: templateclass Tclass Point2{ Point2( T x,T y ) : x(x),y(y) {} T x; T y; Point2T operator+( PointT const other ) const { return PointT(x+other.x,y+other.y); } T sumComponents() const { re
我来自C并试图绕着 scala的类型系统.

考虑以下C模板类:

template<class T>
class Point2
{
  Point2( T x,T y ) :
     x(x),y(y)
  {}

  T x;
  T y;
  Point2<T> operator+( Point<T> const& other ) const
  {
     return Point<T>(x+other.x,y+other.y);
  }
  T sumComponents() const { return x+y; }
}

Point2<Double> p0(12.3,45.6) 
Point2<Double> p1(12.3,45.6) 
Point2<Double> p = p1+p2
Double d = p1.sumComponents()

我发现我想写这样的东西:

case class Point2[ T ] (x:T,y:T) {
   def +() Point2[T]: = x+y
   def sumComponents() T: = x+y
}

或者,(因为编译有问题),

trait Addable[T] {   // Require T supports the + operatory
   def +( that:T ):T
}
case class Point2[ T<:Addable[T] ] (x:T,y:T) {
   def +() Point2[T]: = x+y
   def sumComponents() T: = x+y
}

这同样有问题,因为我不能要求Double扩展Addable.

一般来说,我发现scala的类型系统使用了一组我不太了解的约束.

在scala中实现上述内容的惯用方法是什么?

那么C模板程序员理解scala中泛型限制的正确方法是什么? (为什么我不能在scala中执行此操作?例如,是因为泛型是在实例化之前编译的吗?)

解决方法

我创建了一个库 template.scala.您可以使用该库来创建C风格的模板,避免复杂的含义.

import com.thoughtworks.template
case class Point2[T](x:T,y:T) {
   @template def +(rhs: Point2[_]) = Point2(x + rhs.x,y + rhs.y)
   @template def sumComponents() = x + y
}

println(Point2(1,3).sumComponents()) // Output: 4
println(Point2(1,3) + Point2(100,200)) // Output: Point2(101,203)

请注意,您甚至可以加两个具有不同组件类型的Point2.

println(Point2(1.5,0.3) + Point2(100,200)) // Output: Point2(101.5,200.3)

甚至嵌套的Point2:

// Output: Point2(Point2(10.1,20.2),Point2(101.0,202.0))
println(Point2(Point2(0.1,0.2),Point2(1.0,2.0)) + Point2(Point2(10,20),Point2(100,200)))

它的工作原理是因为@template函数是将在调用站点内联的代码模板.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读