Hi,
Is the below example the “best” way to limit the types that can be passed to a function?
I would like to only allow Int64 and Float64, i.e. I want the function definition to be either vadd(::Float64,::Float64) or vadd(::Float64,::Float64). I don’t want to allow vadd(::Float64,::Int64) for example.
module TT
const tt = Union{Float64, Int64}
function vadd(a::T, b::T) where T <:tt
return a+b+oneunit(T)
end
end
You code looks fine. Is there anything in particular you dislike? Depending on your application, it could be that just checking if the types are the same is sufficient, e.g. vadd(a::T, b::T) where {T}. That way you code remains a bit more generic. (But like Benny said, nothing wrong with your approach.)
As a side note, I would capitalize tt (so Tt or another name starting with uppercase), as it is the identifier of a type, and per style guide they should be capitalized.
I would add that this also solves the problem of the mixed float and int input:
julia> f(a::T,b::T) where T = 1
f (generic function with 1 method)
julia> f(1, 1.0)
ERROR: MethodError: no method matching f(::Int64, ::Float64)
while still remaining general such that Float32s, or Int32 are also accepted, for example (it may be that the definition of the union type is not necessary for what you want).