简体   繁体   中英

Recover type in parametric composite type

In Julia (< 0.6), when creating a parametric composite type such as MyType{T} , is there a clean way to recover T from an instance of that type?

Take their example from the doc:

type Point{T}
    x::T
    y::T
end

I can create an object p = Point(5.0,5.0) , T here will be matched to Float64 so that the corresponding object is a Point{Float64} . Is there a clean way to recover Float64 here?

I could do

typeof(p.x)

But it feels like that's not the right thing to do.

When you need the type parameter, you should define a parametric method. That is the only proper way to access the type parameter.

So for a Point ,

function doSomething{T}(p::Point{T}) 
    // You have recovered T  
    println(T)
end

The type is saved in the class information:

typeof(Point(1, 2)).parameters # -> svec(Int64)

It's more general than writing a specific function for it, but I'm not sure it's considered official.

There's also fieldtype

fieldtype(typeof(Point(1.0, 1.0)), :x) # --> Float64
fieldtype(Point, :x) # --> T
fieldtype(Point{Int64}, :x) # --> Int64

Not sure how that's any better than just getting the type of the instance though.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM