Scala可变数量的参数,它们是F边界类型的子类

时间:2018-08-10 14:22:32

标签: c++ scala types generic-programming f-bounded-polymorphism

在C ++中,我可以创建一个可变参数函数模板,如下所示:

#include <tuple>

// helper to loop over tuple
template <std::size_t I = 0, typename FuncT, typename... Args>
void for_each(std::tuple<Args...>& tuple, FuncT func) {
  func(std::get<I>(tuple));
  if constexpr (I + 1 < sizeof...(Args)) {
    for_each<I + 1, FuncT, Args...>(tuple, func);
  }
}

template <class A, class B, class Derived>
struct FBounded {
  auto foo() { return static_cast<Derived *>(this); }
  auto baz() { return static_cast<Derived *>(this); }
};

class Child1 : public FBounded<const char*, const char*, Child1> {};
class Child2 : public FBounded<bool, int, Child2> {};
class Child3 : public FBounded<double, const char*, Child3> {};

template <class... A, class... B, class... SubTypes>
static auto func(FBounded<A, B, SubTypes>... elems) {
  auto args = std::tuple(elems...);
  for_each(args, [](auto x) { x.foo()->baz(); });
}

int main() {
  auto c1 = Child1();
  auto c2 = Child2();
  auto c3 = Child3();

  func(c1, c2, c3);
}

我想在Scala中重新创建此行为。这是我到目前为止的内容:

class FBounded[A, B, T <: FBounded[A, B, T]] {
  def foo(): T = this.asInstanceOf[T]
  def baz(): T = this.asInstanceOf[T]
}

class Child1 extends FBounded[Int, Double, Child1] {}
class Child2 extends FBounded[String, String, Child2] {}
class Child3 extends FBounded[Int, String, Child3] {}

def func(elems: Seq[FBounded[_, _, _]]) = {
    elems.foreach(_.foo.baz)
}


val c1 = new Child1()
val c2 = new Child2()
val c3 = new Child3()

func(c1, c2, c3)

我收到错误:

error: value baz is not a member of _$3
elems.foreach(_.foo.baz)
              ^

我相信这与Scala填写占位符类型有关,但我不确定。

1 个答案:

答案 0 :(得分:1)

FBounded[_, _, _]类型是某种看起来像这样的存在类型的快捷方式

FBounded[A, B, T] forSome { type A; type B; type T <: FBounded[A, B, T] }

无论出于何种原因,编译器都拒绝为类型参数T推断正确的f边界(至少我无法做到这一点)。

我想这可能与existential types are dropped in Dotty之所以联系起来。

这是一种可以完全避免存在类型的解决方法:

class FBounded[A, B, T <: FBounded[A, B, T]] {
  self: T =>
  def foo: T = self
  def baz: T = self
  def wrap: FBE = new FBE {
    type a = A
    type b = B
    type t = T
    val value: t = self
  }
}

class Child1 extends FBounded[Int, Double, Child1] {}
class Child2 extends FBounded[String, String, Child2] {}
class Child3 extends FBounded[Int, String, Child3] {}

/** Wrapper for FBounded existential types */
abstract class FBE {
  type a
  type b
  type t <: FBounded[a, b, t]
  val value: t
}

def func(elems: FBE*) = {
  elems.map(_.value.foo.baz)
}

val c1 = new Child1()
val c2 = new Child2()
val c3 = new Child3()

func(c1.wrap, c2.wrap, c3.wrap)

它不依赖于存在的FBounded[_, _, _],而是使用包装器类FBE来保存包含所有类型和所有约束的长列表。使用FBEfunc似乎可以正常工作:

def func(elems: FBE*) = {
  elems.map(_.value.foo.baz)
}

因为它可以更明确地写为:

def funcMoreExplicit(elems: FBE*) = {
  elems.map(e => {
    val v: e.t = e.value
    val fooRes: e.t = v.foo
    val bazRes: e.t = fooRes.baz
    bazRes
  })
}

我们可以使用e.t提供的显式路径相关类型FBE.t获得中间结果。