Parameterize type with value (not type)

Hey,

I want to implement a parametric type (container of defined length), i.e., something like MyContainer{Int64, 2}([1, 1]) should be a valid call to a constructor.
To me this looks very similar to the Array types (although they are only parameterized in terms of their dimensions).
The documentation on parametric types does not seem to cover this case explicitly and the Julia implementation of Arrays in the GitHub repos is a wee bit too abstract for me x)

My current solution appears a bit ‘hackish’ to me:

struct MyContainer{T,N}
    values::Vector{T}
    MyContainer{T,N}(values::Vector{T}) where{T,N} = isa(N, Int) & (N == length(values)) ? new(values) : error("")
end
MyContainer(values) = MyContainer{eltype(values),length(values)}(values)
MyContainer([1,1])

Is there a cleaner way of doing this?

That looks fine, but maybe this is a little bit cleaner:

struct MyContainer{T,N}
    values::Vector{T}
    function MyContainer{T,N}(values::Vector{T}) where {T,N}
        N === length(values) || error("some nice message")
        return new{T,N}(values)
    end
end

Edit: I am not sure what the purpose of your code is, but you might find StaticArrays useful.

2 Likes