Restrict type of value type parameter

question

#1

I am declaring a parametric type struct A{L} end, where L should be an integer. For example, in NTuple{N,T}, the N parameter is restricted to be an integer. What is the recommended way to achieve this behavior on my custom time? I could not find the source code of NTuple.


#2

I think that NTuple per se does not check that N is an integer, Vararg (which it is aliased to) does.

For structs, the recommended solution is to check in the inner constructor, eg

struct A{L}
    function A{L}() where L
        @assert L isa Integer
        new{L}()
    end
end

A(L::Integer) = A{L}()          # convenience constructor

A(1)                            # OK
A("a fish")                     # error

#3

PS: the source of NTuple is in boot.jl. It is nothing more than

const NTuple{N,T} = Tuple{Vararg{T,N}}

There is no magic. Being able to write such core constructs in Julia lends a certain elegance to the language.


#5

Thanks. If Vararg is also in Julia, do you know where is the source?


#6

I think that Vararg is implemented in C.