Numbers as generic parameter

I had a few questions on the use of integers as generic parameters. I see the call to do this quite often, primarily so that we can have fixed size arrays and matrices.

Practically, what is the highest integer which you would need in real world use for these types of features?

Some of the proposals also allow Strings as parameters. What would be the use-case for that?

I ask because I wonder if we actually need all of that complexity, or if we can implement something simpler that works for the major use-cases (e.g. fixed arrays).

Would it be possible for the compiler to auto-generate extremely simple Types when it finds IntegerLiterals used as arguments for generic parameters. They would all adhere to a simple protocol:

protocol StaticInteger {
    static var value:Int {get}
}

Which would be used as such:

struct FixedArray<Size:StaticInteger> {
    var count:Int {return Size.value}
    ...
}

When the compiler encounters an Integer literal as an argument to a generic parameter (e.g. StaticArray<3>), it generates a simple type (if that type hasn't already been created):

struct StaticInteger3:StaticInteger {
    static var value:Int {return 3}
}

It seems to me that doing something like this (i.e. a protocol in the standard library + generation of simple types adhering to that protocol) would be quicker/simpler/easier than creating a new concept of allowing arbitrary values to be passed as generic parameters.

Am I missing something important?

The real problem is you still can't implement the storage of this fixed array type without a heap allocation.

2 Likes