更新:修改代码以使用宏注释,但仍然缺少某些内容
以下代码有效(下面的问题):
object MyTypes {
trait RealType
class Container[RT <: RealType] {
this: RT =>
}
trait SomeRealType extends RealType
trait PartialRealType extends RealType {
val needed: Int
}
}
import MyTypes._
object Container {
import scala.reflect.macros.blackbox.Context
import scala.language.experimental.macros
def helper[RT <: RealType : c.WeakTypeTag](c : Context) : c.Expr[RT] = {
import c.universe._
val weakRT = weakTypeOf[RT]
val genTree = q"new Container[$weakRT] with $weakRT {}"
c.Expr(genTree)
}
def apply[RT <: RealType] : Container[RT] with RT = macro helper[RT]
}
val ok = new Container[SomeRealType] with SomeRealType
val ok_quasi = Container[SomeRealType]
我希望能够运行以下内容:
val partial = Container[PartialRealType]{val needed: Int = 0}
我试图这样做:
object Container {
import scala.reflect.macros.blackbox.Context
import scala.language.experimental.macros
def helper[RT <: RealType : c.WeakTypeTag](c : Context)(body: c.Expr[Unit]) : c.Expr[RT] = {
import c.universe._
val weakRT = weakTypeOf[RT]
val genTree = q"new Container[$weakRT] with $weakRT { $body }"
c.Expr(genTree)
}
def apply[RT <: RealType](body: Unit) : Container[RT] with RT = macro helper[RT]
}
然而,这不起作用。