Using type parameters (with where) in functions

I’ve tried the following:

f{T}() where T = typeof(T)
f{Int64}()

with no luck, the first line returning UndefVarError: f not defined. As I understood type parameters, things like this should be possible, since the type is inferred from the method signature (where), but this seems to work only for types, not functions or methods, is this correct?

It’s not clear what you are trying to do. How about

julia> f(x::T) where {T} = T
f (generic function with 1 method)

julia> f(3)
Int64

No that’s not supported since type parameter is a property of the method and not the function. You can either do f(Int64) (and write function to just take a type as argument) or explicitly make f a type i.e. struct f{T} end and define call on that.

3 Likes

It’s a simplistic example of a generic function (method), which doesn’t have mentioning of T in its parameters signature.

Does this have any overhead worth mentioning, or in the end is no different than using standard methods?

It is not recommended since it offer no advantage over passing the type as a normal parameter. Using special type for this should not add runtime overhead when things are properly inferred. There are different kind of overhead when things aren’t inferrend in either cases.