"channel" 类型的字段给出错误 "Cannot default-initialize a variable with generic type"
A field of "channel" type gives error "Cannot default-initialize a variable with generic type"
在此代码中,我创建了一个 class,其中包含一个频道,该频道可在初始化时根据请求打开。为此,我传递了一个标志来指示频道是否打开(连同其文件名)。
class Myclass
{
var writeflag : bool;
var output : channel;
proc init( writeflag = false, filename = "" )
{
this.writeflag = writeflag;
if writeflag { // (1)
assert( filename != "" );
this.output = openwriter( filename );
} // (2)
}
}
proc main()
{
var a = new owned Myclass( writeflag = true,
filename = "test.out" );
a.output.writeln( 123 );
}
但是,编译器拒绝上述代码并显示消息:
myclass.chpl:6: error: Cannot default-initialize a variable with generic type
myclass.chpl:6: note: 'not-fully-instantiated' has generic type 'channel'
另一方面,如果我注释掉 (1) 和 (2),代码将按预期运行并创建 "test.out"。我猜这个问题与 channel
的通用性质有关(根据错误消息),但不太确定如何适当地编写这样的代码...
I guess the problem is related to the generic nature of channel (according to the error message), but not very sure how to write such a code appropriately...
您走在正确的轨道上。 channel record 有一些必须在编译时提供的参数字段。您可以在字段声明中指定这些参数:
var output : channel(writing=true, kind=iokind.dynamic, locking=false);
根据回答和评论中的建议,我修改了我的代码如下。因为具体的类型有点难记,所以我创建了一个类型别名,并在class规范中使用了它(这里用locking=true
来概括,请看docs)。
// utils.chpl
type Writer = channel( true, iokind.dynamic, true );
type Reader = channel( false, iokind.dynamic, true );
// test.chpl
use utils only Writer;
class Myclass
{
var writeflag : bool;
var output : Writer;
// ... the remaining is the same
}
在此代码中,我创建了一个 class,其中包含一个频道,该频道可在初始化时根据请求打开。为此,我传递了一个标志来指示频道是否打开(连同其文件名)。
class Myclass
{
var writeflag : bool;
var output : channel;
proc init( writeflag = false, filename = "" )
{
this.writeflag = writeflag;
if writeflag { // (1)
assert( filename != "" );
this.output = openwriter( filename );
} // (2)
}
}
proc main()
{
var a = new owned Myclass( writeflag = true,
filename = "test.out" );
a.output.writeln( 123 );
}
但是,编译器拒绝上述代码并显示消息:
myclass.chpl:6: error: Cannot default-initialize a variable with generic type myclass.chpl:6: note: 'not-fully-instantiated' has generic type 'channel'
另一方面,如果我注释掉 (1) 和 (2),代码将按预期运行并创建 "test.out"。我猜这个问题与 channel
的通用性质有关(根据错误消息),但不太确定如何适当地编写这样的代码...
I guess the problem is related to the generic nature of channel (according to the error message), but not very sure how to write such a code appropriately...
您走在正确的轨道上。 channel record 有一些必须在编译时提供的参数字段。您可以在字段声明中指定这些参数:
var output : channel(writing=true, kind=iokind.dynamic, locking=false);
根据回答和评论中的建议,我修改了我的代码如下。因为具体的类型有点难记,所以我创建了一个类型别名,并在class规范中使用了它(这里用locking=true
来概括,请看docs)。
// utils.chpl
type Writer = channel( true, iokind.dynamic, true );
type Reader = channel( false, iokind.dynamic, true );
// test.chpl
use utils only Writer;
class Myclass
{
var writeflag : bool;
var output : Writer;
// ... the remaining is the same
}