获取参数类型的参数 [英] Get parameters of a parametric type

查看:73
本文介绍了获取参数类型的参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我定义了这样的类型

Suppose I define a type like that

type Point{Tx, Ty} end

然后,我创建一个这种类型的变量,例如,

Then I create a variable of this type, for example,

a = Point{Int64, :something}()

现在,我只知道我可以通过typeof(a)获得a的类型.即Point{Int64, :something}. 但是,我需要的只是参数TxTy.

Now, I only know that I can get the type of a by typeof(a). That is, Point{Int64, :something}. But, what I need is just the parameters Tx and Ty.

有什么方法可以获取这些参数TxTy?

Are there ways that I can get those parameters Tx and Ty?

推荐答案

您可以按以下方式定义函数

You can define a function as follows

eltypes{Tx,Ty}(::Type{Point{Tx, Ty}}) = (Tx, Ty)
eltypes(p) = eltypes(typeof(p))

(此处::Type{Point{Tx, Ty}}匹配类型为Point{Tx, Ty}的参数)并使用它

(here ::Type{Point{Tx, Ty}} matches an argument of type Point{Tx, Ty}) and use it

julia> eltypes(Point{Int, Float64}())
(Int64,Float64)

这是一个常用的习惯用法,例如在Base中有类似的功能

This is a frequently used idiom, for example in Base there is the similar function

eltype{T}(::Type{Set{T}}) = T
eltype(x) = eltype(typeof(x))

这篇关于获取参数类型的参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆