tk3369
June 17, 2019, 7:23pm
1
For parametric type, does the constructor not call convert
automatically?
julia> struct Foo3{T}
a::T
b::Float64
end
julia> Foo3(1,2)
ERROR: MethodError: no method matching Foo3(::Int64, ::Int64)
Closest candidates are:
Foo3(::T, ::Float64) where T at REPL[25]:2
Stacktrace:
[1] top-level scope at none:0
julia> Foo3(1,2.0)
Foo3{Int64}(1, 2.0)
It works properly for regular types:
julia> struct Foo2
x::Int
y::Float64
end
julia> Foo2(1,2)
Foo2(1, 2.0)
The constructor DOES call convert.
julia> Foo3{Int}(1, 2)
Foo3{Int64}(1, 2.0)
You can see clearly from the error message and the backtrace that the error happens on the call of Foo3
, not inside the constructor. There simply isn’t a constructor defined in this case to guess the type parameter for you.
3 Likes
tk3369
June 17, 2019, 10:18pm
4
Yes, it would be nice if it just works without having to specify the type parameter.
You could manually define an outer constructor though:
Foo3(a::T, b) where {T} = Foo3{T}(a, b)
tk3369
June 20, 2019, 6:29am
6
That’s a good idea! If such outer constructor were “auto-generated” then it would be super-awesome.