我怀疑如何使用where语法在Julia0.6中使用抽象类型限制参数类型参数。
考虑一个示例,其中我想要创建一个参数抽象类型,接受整数,并定义从它继承的结构。如果我试着:
abstract type AbstractFoo{T} where T<: Integer end它失败了,但是我可以使用非where语法。
abstract type AbstractFoo{T<:Integer} end在此情况下,如何实现我的子类型?
mutable struct Foo{T} <: AbstractFoo{T} where T <: Integer
bar::T
end也失败(Invalid subtyping)。我可以再次绕过where语法
mutable struct Foo{T<:Integer} <: AbstractFoo{T}
bar::T
end但这似乎是多余的(因为T已经被限制为整数)。2.我可以把它省去吗?
mutable struct Foo{T} <: AbstractFoo{T}
bar::T
end最后,随着内部构造函数语法的取消,是否可以将内部构造函数定义为:
mutable struct Foo{T} <: AbstractFoo{T}
bar::T
Foo{T}(x::T) where T = new(x)
end这使得Foo(3)不可能--要求我使用Foo{Int}(3)。3.这是故意的,还是有更好的解决办法?编辑:我想对于内部构造函数问题,我总是可以定义一个外部构造函数Foo(x::T) where {T} = Foo{T}(x)。
发布于 2017-05-30 15:18:22
我会写:
abstract type AbstractFoo{T<:Integer} end
mutable struct Foo{T} <: AbstractFoo{T}
bar::T
Foo(x::T) where T = new{T}(x)
end( 1)限制x到Integer 2)允许写Foo(2)
关于这些问题:
Integer上,但是您可能会得到更糟糕的错误消息,因为它是从AbstractFoo而不是Foo得到的。您的用户可能不会注意到Foo是AbstractFoo的一个子类型,因此会感到困惑。where语法的主要目的之一。在新语法中,T{S}总是指定T的类型参数,where S引入函数的类型参数。因此,Foo{T}(x) where T =定义了Foo{Int}(2)应该做什么,Foo(x::T) where T =定义了Foo(2)应该做什么。在引入where之后,不再存在“内部构造函数”。您可以在任何结构(不一定是该类型的构造函数)中定义任何函数,并在类型定义之外定义任何构造函数--唯一的区别是在类型定义中,您可以访问new。发布于 2017-05-30 13:55:09
我在这里的立场有点不稳定,但不久前我有一个similar问题。基于我从中学到的东西,我建议你尝试一下,看看它是如何为你工作的:
abstract type AbstractFoo{T} end
mutable struct Foo{T<:Integer} <: AbstractFoo{T}
bar::T
end在我看来,将参数限制在具体类型上而不是抽象类型上似乎是最合理的。
https://stackoverflow.com/questions/44262404
复制相似问题