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

4

使用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
2个回答

5
< p >参数化类型 < code >T 实际上并没有用于表达任何类型之间的关系,因此使用它时几乎没有理由,这只会增加不必要的复杂性。 < p >这里有一个例子,在这个例子中使用参数化类型是必要的:
function pow{T <: Real}(base::T, exponent::T)
    base^power
end

在这种情况下,T 是必要的,以强制确保 baseexponent 具有相同的类型,限制是该类型必须是 Real 的子类型。
相比之下,以下是相同的函数,不使用参数化类型:
function pow(base:: Real, exponent:: Real)
    base^power
end

现在这个函数要求baseexponent都是Real的子类型,但是没有类型关系来强制要求两者都是Real的相同子类型。


4

建议使用 f(x::Real)。额外的不必要类型参数会使编译器难以处理并减慢动态分派速度,同时对其他人阅读也更加困难。

请参考 风格指南

Don’t use unnecessary static parameters

A function signature:

foo{T<:Real}(x::T) = ...

should be written as:

foo(x::Real) = ...

instead, especially if T is not used in the function body. Even if T is used, it can be replaced with typeof(x) if convenient. There is no performance difference. Note that this is not a general caution against static parameters, just against uses where they are not needed.

Note also that container types, specifically may need type parameters in function calls. See the FAQ Avoid fields with abstract containers for more information.


嘿,foo{x::T, y::T}(x::T, y::T)foo(x::T, y::T) where {x::T, y::T}怎么样?哪种风格更受欢迎?foo{x::T, y::T}(x::T, y::T)在0.6版本中是否已被弃用? - amrods
你是指 foo{T}(x::T, y::T) 吗?如果你使用的是0.6版本,请优先考虑 foo(x::T, y::T) where {T} - Fengyang Wang

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接