我对使用where
语法如何使用julia 0.6中的抽象类型限制参数类型的类型参数表示怀疑.
考虑一个示例,我想创建一个采用整数的参数化抽象类型,并定义从中继承的结构.如果我尝试:
abstract type AbstractFoo{T} where T<: Integer end
Run Code Online (Sandbox Code Playgroud)
它失败了,但我可以使用非where
语法
abstract type AbstractFoo{T<:Integer} end
Run Code Online (Sandbox Code Playgroud)
鉴于此,我如何实现我的子类型
mutable struct Foo{T} <: AbstractFoo{T} where T <: Integer
bar::T
end
Run Code Online (Sandbox Code Playgroud)
也失败了(Invalid subtyping
).我可以where
再次绕过语法
mutable struct Foo{T<:Integer} <: AbstractFoo{T}
bar::T
end
Run Code Online (Sandbox Code Playgroud)
但这似乎是多余的(因为T已经被限制为整数).我可以把它留下来吗?:
mutable struct Foo{T} <: AbstractFoo{T}
bar::T
end
Run Code Online (Sandbox Code Playgroud)
最后,随着内部构造函数语法的弃用,有没有办法将内部构造函数定义为:
mutable struct Foo{T} <: AbstractFoo{T}
bar::T
Foo{T}(x::T) where T = new(x)
end
Run Code Online (Sandbox Code Playgroud)
这使得Foo(3)
不可能 - 要求我使用Foo{Int}(3)
.这是故意还是有更好的解决方法?编辑:我想对于内部构造函数问题,我总是可以定义一个外部构造函数Foo(x::T) where {T} = Foo{T}(x)
.
我会写:
abstract type AbstractFoo{T<:Integer} end
mutable struct Foo{T} <: AbstractFoo{T}
bar::T
Foo(x::T) where T = new{T}(x)
end
Run Code Online (Sandbox Code Playgroud)
这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
. 归档时间: |
|
查看次数: |
943 次 |
最近记录: |