是否可以从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?
推荐答案
您可以使用 invoke
函数
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
如果您对使用比调用"更直观的名称有任何想法,请在下面发表评论.
If you have any thoughts on what a more intuitive name than "invoke" would be, please post a comment below.
这篇关于是否可以从Julia中的覆盖函数调用重载函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!