f(x :: Real)和f {T <:Real}(x :: T)之间的区别?

amr*_*ods 4 types julia

f(x::Real)和定义函数之间有什么区别f{T <: Real}(x::T)吗?

@code_warntype 给出相同的输出

function f(x::Real)
    x^2
end

function g{T <: Real}(x::T)
    x^2
end
Run Code Online (Sandbox Code Playgroud)

Ale*_*ica 5

参数类型 T实际上并没有用来表达类型之间的任何关系,所以有它的用途,它只是增加了不必要的复杂性没有什么道理.

这是一个例子,其中使用参数类型是必要的:

function pow{T <: Real}(base::T, exponent::T)
    base^power
end
Run Code Online (Sandbox Code Playgroud)

在这种情况下,T必须强制执行两者baseexponent具有相同的类型,并且该类型必须是子类型的限制Real.

相反,这里是相同的功能,不使用参数类型:

function pow(base:: Real, exponent:: Real)
    base^power
end
Run Code Online (Sandbox Code Playgroud)

现在,这个功能需要两个baseexponent是亚型Real,但有强制执行,无论是同一亚型的任何类型的关系Real.