捕获为值时函数调用出错

Error on function call when captured as values

所以我有一个程序,其中有一个函数需要作为参数传递给另一个函数调用。所以我是 运行 一个测试用例。假设有两个 classes Abstract 和 Concrete,后者是前面的 child class。

// This enum is designed to distinguish between 'int', 'real', and 'bool' types
enum myTypes { i, r, b };

// This helper function converts from a type to one of the above enum values
proc typeToEnum(type t) {
  select t {
    when int do
      return myTypes.i;
    when real do
      return myTypes.r;
    when bool do
      return myTypes.b;
    otherwise
      compilerError("Unexpected type in typeToEnum()");
  }
}

// This is an abstract class that isn't good for much other than
// supporting the ability to mix various sub-class instantiations
// within a data structure.
//
class AbstractDataArray {
  // This stores information sufficient for determining a concrete
  // subclass's static type
  var concType: myTypes;
  const rank: int;

  // This is its initializer
  proc init(type t,rank) {
    this.concType = typeToEnum(t);
    this.rank = rank;
  }

  // This is a dynamically dispatched method
  proc printMe() {
    writeln("I am a generic Abstract class");
  }
}

// This is a concrete class that contains everything important through
// generic fields
//
class Concrete: Abstract {
  type t;    // the type of elements stored
  var x: t;  // an example element of that type

  // The class's initializer
  proc init(x) {
    super.init(x.type);
    this.t = x.type;
    this.x = x;
  }

  // The class's override of the dynamically dispatched method
  override proc printMe() {
    writeln("I am a Concrete class with type ", t:string, " and value ", x);
  }

  // This is a non-dynamically dispatched method, because its return
  // type will vary across classes in the hierarchy, so it can't be
  // inherited.
  //
  proc getValue() {
    return x;
  }
}

我需要作为参数传递的函数如下

proc rhs(u:shared Abstract,t:real){
   // Does some stuff by changing abstract to one of concerete types
   // returns rh which is object of class Concerete typecasted to class Abstract
   return rh:Abstract;
}

var a = rhs;
a(U_0,1.20);  // Assume U_0 has been defined somewhere above and is an object of class Concerete 

在 运行 最后一个代码上,输出是

Tests/sphinx_solvingPDE.chpl:81: error: in call to 'this', cannot pass result of coercion by reference
Tests/sphinx_solvingPDE.chpl:81: note: implicit coercion from 'shared DataArray(real(64),1,false)' to 'shared AbstractDataArray'
Tests/sphinx_solvingPDE.chpl:80: note: when passing to 'const ref' intent formal 'u'

所以解决上述问题很简单。我将变量类型转换为 Abstract,然后将其传递给函数,而不是直接传递它。

var arg = U_0:AbstractDataArray;
a(arg,1);