On Mon, 2016-09-12 at 16:07, Yichao Yu <yyc1...@gmail.com> wrote:
> On Mon, Sep 12, 2016 at 9:52 AM, Neal Becker <ndbeck...@gmail.com> wrote:
>
>> Taking the following example:
>>
>> type Point{T<:Real}
>>          x::T
>>          y::T
>> end
>>
>> I can construct a Point taking the type "T" from the argument types.
>> Or I can explicity specify the type
>>
>> Point{Int32}(2,2)
>>
>> But I'd like to be able to specify a default type:
>>
>> type Point{T<:Real=Int32}
>>
>> for example, so that an unqualified
>> Point(2,2)
>>
>> would produce Point{Int32}, while still allowing explicity
>> Point{Int64}(2,2)
>>
>
> Overload `Point` to do exactly that.
>
> `Point(x, y) = Point{Int32}(x, y)`
>
> Note that having types as first class object (different from c++) we can't
> have default type parameters at type level since we need the `Point` in
> `Point` and `Point{Int64}` to mean exactly the same thing.

This actually doesn't work because the default constructor is more
specific for (Int,Int) arguments:

Providing this constructor works:

Point{T<:Real}(x::T,y::T) = Point{Int32}(x,y)

Note, this is quite fiddly as these don't work:

Point(x,y) = Point{Int32}(x,y)
Point{T}(x::T,y::T) = Point{Int32}(x,y)

as the default constructor has the signature Point{T<:Real}(x::T,y::T)
which is more specific than above two non-working functions.

Depending on your needs, you can also add above catch-all:
Point(x,y) = Point{Int32}(x,y)

then this works too:

julia> Point(4,5.)
Point{Int32}(4,5)

Reply via email to