Store class(T) in an array

I’d like to store the successive instances of a generic class in an array.

The following code doesn’t compile, which is expected.

class Test(T)
  class_property instances = [] of Test(T) # => Error ! 
  def initialize(@var : T)
  end
end

x = Test.new(33)
y = Test.new("abc")

Error: can’t infer the type parameter T for the generic class Test(T). Please provide it explicitly

Is there any way of doing this, given that type T is not known in advance?

I think the problem is T isn’t known in the class scope, only in the instance scope when instantiated. Workaround would be like add some abstract non-generic class and inherit from that. Then type the array using that abstract parent type.

Yes, it works! Thanks a lot @Blacksmoke16 !
Here is the modified code:

abstract class ATest
  class_property instances = [] of ATest
end

class Test(T) < ATest
  def initialize(@var : T)
    ATest.instances << self
  end
end

x = Test.new(33)
y = Test.new("abc")

p! ATest.instances

which outputs:

ATest.instances # => [#<Test(Int32):0x7b9eff8bff30 @var=33>, #<Test(String):0x7b9eff8be580 @var=“abc”>]

You can keep the class property in Test(T), you just need ATest for typing it.

Hmm, moving class_property instances from Atest to Test(T) gives an error message:

Error: undefined method ‘instances’ for ATest.class

Class methods aren’t visible by default in the instance scope. Could do like self.class.instances, or just access it directly @@instances << self.

Yes, it works with both syntaxes.
Thank again.