Maik Klein
Maik Klein

Reputation: 16148

Generics with constraints

type VBO<'T when 'T : (new : unit -> 'T) and 'T : struct and 'T :> ValueType> = 
...

type VAO =
    static member Create(vboList : VBO<'T> list) = 
...

Now when I do

val a : VBO<Vector3>
val b : VBO<float>

VAO.Create([a;b])// F# forces vboList to be of type VBO<Vector3> list

I just want my vboList to treat every type the same as long as they fulfill the following constraint <'T when 'T : (new : unit -> 'T) and 'T : struct and 'T :> ValueType>

Would this be possible?

Upvotes: 2

Views: 181

Answers (2)

Tarmil
Tarmil

Reputation: 11362

One thing you can do is to create a base parameterless type and use that as the elements of your list:

type VBO_Base =
    class end

type VBO<'T when 'T : (new : unit -> 'T) and 'T : struct and 'T :> ValueType> = 
    inherit VBO_Base
    ...

type VAO =
    static member Create(vboList : VBO_Base list) = 
    ...

val a : VBO<Vector3>
val b : VBO<float>

VAO.Create([a;b]) // both a and be get automatically downcast to VBO_Base

And in fact you can call this base type VBO, since .NET allows two different types to have the same name if they have a different number of parameters.

Upvotes: 1

John Palmer
John Palmer

Reputation: 25516

The problem is that a and b have different types.

Lists can only contain elements of a single type.

For example [a;a] is fine as is [b;b] but [a;b] is not.

One way around this would be to make a new class heirachy were you have a new float and Vector3 that both inherit from the same base class and you could downcast the objects to that type.

Upvotes: 1

Related Questions