Suppose I have an abstract type A{V}
and two structs B{V}
and C{V}
, for example
abstract type A{V} end
struct B{V} <: A{V}
x::V
end
struct C{V} <: A{V}
x::V
end
Now suppose I have a function f
that accepts A{V}
. In other words, what is coming in could either be B{V}
or C{V}
. I want to construct an instance of the appropriate concrete type where I have switched out V
for an Int
. If I do it for each concrete type, that’s super easy. Here’s an example:
f(x::B{V}) where {V} = B{Int}(3)
f(x::C{V}) where {V} = C{Int}(3)
But I would like to the above generically. For all I know, there could be tons more subtypes of A{V}
out there. I would like to write a function f(x::A{V})
that somehow figures out what the hidden B
or C
is and swaps out the V
for an Int
.
I know that in general we cannot assume anything about how the subtype of A{V}
is parametrized. But it still makes sense to want to get the “appropriate” type based on the input type that is a subtype of A{Int}
, irrespective of / ignoring V
. My question is: how can I write a function f(x::A{V})
that returns something that is a subtype of A{Int}
but has the same “concrete form” as what came in? If this requires writing a specialized method (e.g. some sort of convert
rule) for each concrete subtype of A
, I’m fine with that, I would just like to know what the solution is