To generalize this idiom a bit, I think I'd write it as:
Base.convert(::Type{Float64}, a::MyNum) = convert(Float64, a.x)
f(a) = f(convert(Float64, a))
f(a::Float64) = 2. # real algorithm
Of course, this will also allow things like `f(1)`.
On Tuesday, March 15, 2016 at 10:18:30 AM UTC-4, Stefan Karpinski wrote:
>
> No, there is never any implicit conversion of arguments in Julia. However,
> all you need to do is add a method to f to get it to do what you want:
>
> f(a::MyNum) = convert(Float64, a.x)
>
> On Tue, Mar 15, 2016 at 6:54 AM, Carlo Lucibello <[email protected]
> <javascript:>> wrote:
>
>>
>>
>> Il giorno martedì 15 marzo 2016 11:51:31 UTC+1, Carlo Lucibello ha
>> scritto:
>>>
>>> Is it possible to have user defined implicit conversion in Julia?
>>>
>>> This is an example of how I imagine it should work:
>>>
>>> type MyNum
>>> x
>>> end
>>>
>>> implicit_convert(::Type(Float64), a::MyNum) = convert(Float64, a.x)
>>>
>>> f(x::Float64) = 2.
>>> f(MyNum(1.)) # error, sadly
>>>
>>> In C++ this behaviour can be obtained overloading
>>>
>> * overloading operator double()
>>
>>> PS I don’t want to use inheritance
>>>
>>>
>>
>