将许多标准方法扩展到新的自定义向量类型 [英] Extend many standard methods to a new custom vector type

查看:9
本文介绍了将许多标准方法扩展到新的自定义向量类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我构建了一个新的向量类型:

I build a new vector type:

type MyType
    x::Vector{Float64}
end

我想将许多标准方法(例如加法、减法、逐元素比较等)扩展到我的新类型.我是否需要为它们中的每一个定义一个方法定义,例如:

I want to extend lots of the standard methods, eg addition, subtraction, element-wise comparison, etc to my new type. Do I need to define a method definition for each of them, eg:

+(a::MyType, b::MyType) = a.x + b.x
-(a::MyType, b::MyType) = a.x - b.x
.<(a::MyType, b::MyType) = a.x .< b.x

或者我可以在这里使用一些语法捷径吗?

or is there some syntactic short-cut I can use here?

推荐答案

这是一个使用 的例子Julia 的元编程:

for op in (:+, :-, :.<)
    @eval ($op)(a::MyType, b::MyType) = ($op)(a.x, b.x)
end

这篇关于将许多标准方法扩展到新的自定义向量类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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