如何重载转换

How to overload convert

我有两种类型 AB。我写了 B(a::A)convert(::Type{B}, a),但这并不能立即使 Array{B}(as::Array{A}) 起作用。我也必须写这个方法吗?根据 the documentation,我希望 Julia 会为我处理剩下的事情。

struct A end
struct B end
B(a::A) = B();
convert(::Type{B}, a) = B(a);

# These work
B(A());
convert(B, A());

# This doesn't
Array{B}([A()]);

这是错误

ERROR: LoadError: MethodError: Cannot `convert` an object of type A to an object of type B
Closest candidates are:
  convert(::Type{T}, !Matched::T) where T at essentials.jl:154
  B(::A) at /home/mvarble/test.jl:3
Stacktrace:
 [1] setindex!(::Array{B,1}, ::A, ::Int64) at ./array.jl:767
 [2] copyto! at ./abstractarray.jl:753 [inlined]
 [3] copyto! at ./abstractarray.jl:745 [inlined]
 [4] Type at ./array.jl:482 [inlined]
 [5] Array{B,N} where N(::Array{A,1}) at ./boot.jl:427
 [6] top-level scope at none:0
 [7] include at ./boot.jl:326 [inlined]
 [8] include_relative(::Module, ::String) at ./loading.jl:1038
 [9] include(::Module, ::String) at ./sysimg.jl:29
 [10] exec_options(::Base.JLOptions) at ./client.jl:267
 [11] _start() at ./client.jl:436

您必须从 Base 添加一个方法到 convert,而不是在当前模块中定义一个新的 convert 函数。因此你应该写:

Base.convert(::Type{B}, a) = B(a)

import Base: convert

在定义 convert 之前,就像您在代码中所做的那样。