Julia 如果泛型类型参数没有';函数体中没有指定?

Julia 如果泛型类型参数没有';函数体中没有指定?,julia,Julia,如果我有 struct X{T} end 以及X上的函数调度,如果方法签名中没有指定,我如何访问函数体中的T?即 function foo(x::X) # can i get T in here? end 这是对julialang slack提出的一个问题的重新表述: 要获得访问权限,只需填写以下表单:最好的方法是定义访问器函数: getparam(::X{T}) where {T} = T 然后你就可以做了 function foo(x::X) T = getparam

如果我有

struct X{T} end
以及
X
上的函数调度,如果方法签名中没有指定,我如何访问函数体中的
T
?即

function foo(x::X)
    # can i get T in here?
end

这是对julialang slack提出的一个问题的重新表述:


要获得访问权限,只需填写以下表单:

最好的方法是定义访问器函数:

getparam(::X{T}) where {T} = T
然后你就可以做了

function foo(x::X)
    T = getparam(x)
    ...
end
只要您没有通过解释器运行julia,所有类型检查都应该在编译时删除。例如:


julia> foo(x::X) = getparam(x) + 1
foo (generic function with 1 method)

julia> foo(X{1}())
2

julia> @code_llvm foo(X{1}())

;  @ REPL[24]:1 within `foo'
define i64 @julia_foo_19216() {
top:
  ret i64 2
}

julia> @code_llvm foo(X{2}())

;  @ REPL[24]:1 within `foo'
define i64 @julia_foo_19221() {
top:
  ret i64 3
}
正如您可能看到的,编译器能够发现它可以在编译时将调用
foo(X{2})
替换为
3
,而不需要任何运行时开销


作为旁注,这应该有助于证明为什么重要。如果我们执行了类似于
foo(X{rand(Int)})
的操作,编译器将无法访问类型参数,直到它在运行时到达
foo
,然后需要为
rand(Int)
最终计算的对象编译特定方法,这将非常缓慢:

julia> @btime foo(X{rand(Int)}())
  2.305 ms (1962 allocations: 125.49 KiB)
-3712756042116422157
噢,真是糟透了!作为比较

julia> bar(x) = x + 1
bar (generic function with 1 method)

julia> @btime bar(rand(Int))
  9.746 ns (0 allocations: 0 bytes)
5990190339309662951
交叉参考