是否可以从 Julia 中的覆盖函数中调用重载函数? [英] Is it possible to call an overloaded function from overwriting function in Julia?
问题描述
问题如下:
我有一个抽象类型 MyAbstract
和派生的复合类型 MyType1
和 MyType2
:
I have an abstract type MyAbstract
and derived composite types MyType1
and MyType2
:
abstract MyAbstract
type MyType1 <: MyAbstract
somestuff
end
type MyType2 <: MyAbstract
someotherstuff
end
我想为 MyAbstract
类型的对象指定一些一般行为,所以我有一个函数
I want to specify some general behaviour for objects of type MyAbstract
, so I have a function
function dosth(x::MyAbstract)
println(1) # instead of something useful
end
这种一般行为对于 MyType1
来说已经足够了,但是当使用 MyType2
类型的参数调用 dosth
时,我希望发生一些额外的事情是特定于 MyType2
的,当然,我想重用现有代码,所以我尝试了以下方法,但没有奏效:
This general behaviour suffices for MyType1
but when dosth
is called with an argument of type MyType2
, I want some additional things to happen that are specific for MyType2
and, of course, I want to reuse the existing code, so I tried the following, but it did not work:
function dosth(x::MyType2)
dosth(x::MyAbstract)
println(2)
end
x = MyType2("")
dosth(x) # StackOverflowError
这意味着 Julia 有一段时间没有意识到我试图将 x
视为它的超类型".
This means Julia did not recognize my attempt to treat x
like its "supertype" for some time.
是否可以从 Julia 的覆盖函数中调用重载函数?我该如何优雅地解决这个问题?
Is it possible to call an overloaded function from the overwriting function in Julia? How can I elegantly solve this problem?
推荐答案
您可以使用调用
函数
You can use the invoke
function
function dosth(x::MyType2)
invoke(dosth, (MyAbstract,), x)
println(2)
end
使用相同的设置,这会给出以下输出而不是堆栈溢出:
With the same setup, this gives the follow output instead of a stack overflow:
julia> dosth(x)
1
2
可以在这里找到关于替换或改进invoke
界面的讨论.我的建议将使语法非常接近您在问题中写的内容:
Discussion can be found here on replacing or improving the interface to invoke
. My proposal would make the syntax very close to what you wrote in your question:
function dosth(x::MyType2)
@invoke dosth(x::MyAbstract)
println(2)
end
如果您对比invoke"更直观的名称有什么想法,请在下方发表评论.
If you have any thoughts on what a more intuitive name than "invoke" would be, please post a comment below.
这篇关于是否可以从 Julia 中的覆盖函数中调用重载函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!