用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)
该参数类型 T实际上并没有用来表达类型之间的任何关系,所以有它的用途,它只是增加了不必要的复杂性没有什么道理.
这是一个例子,其中使用参数类型是必要的:
function pow{T <: Real}(base::T, exponent::T)
base^power
end
Run Code Online (Sandbox Code Playgroud)
在这种情况下,T必须强制执行两者base并exponent具有相同的类型,并且该类型必须是子类型的限制Real.
相反,这里是相同的功能,不使用参数类型:
function pow(base:: Real, exponent:: Real)
base^power
end
Run Code Online (Sandbox Code Playgroud)
现在,这个功能需要两个base和exponent是亚型Real,但有强制执行,无论是同一亚型的任何类型的关系Real.
| 归档时间: |
|
| 查看次数: |
80 次 |
| 最近记录: |