I want to define a subtype (say MyInt
) of Integer
and be able to convert between MyInt
and other Integers
.
I suppose I could use an immutable
or a bitstype
:
immutable MyInt <: supertype(Int)
x::Int
end
Base.convert(::Type{MyInt}, a::MyInt) = a
Base.convert(::Type{MyInt}, a::Integer) = MyInt(convert(Int, a))
Base.convert{T<:Integer}(::Type{T}, a::MyInt) = convert(T, a.x)
Base.show(io::IO, a::MyInt) = show(a.x)
or
bitstype sizeof(Int)*8 MyInt <: supertype(Int)
Base.convert(::Type{MyInt}, a::MyInt) = a
Base.convert(::Type{MyInt}, a::Integer) = reinterpret(MyInt, convert(Int, a))
Base.convert{T<:Integer}(::Type{T}, a::MyInt) = convert(T, reinterpret(Int, a))
Base.show(io::IO, a::MyInt) = show(reinterpret(Int, a))
Is one approach faster/better than the other?
Are there any other considerations?
I noticed in Base.Enums
the use of box
(v0.5) and bitcast
(v0.6).
How do these compare with reinterpret
?
Enums
in v0.5 uses Core.Intrinsics.box
:
Base.convert{T<:Integer}(::Type{T}, x::Enum) = convert(T, box(Int32, x))
Enums
in v0.6 uses Core.Intrinsics.bitcast
:
Base.convert{T<:Integer}(::Type{Integer}, x::Enum{T}) = bitcast(T, x)