C# generics equivalent of C++ template specialization/implicit constror

242 Views Asked by At

Is there any way to emulate C++ template specialization using C# generics and/or rtti?

Consider following functions, implementation details do not matter:

public void DrawShape(Shape sh, Brush brush1, ...) { ... }
public void DrawShape(Shape sh, Func<Brush> brushGetter1, ...) { ... }

The shape can use many brushes, and any combination between getter delegate and raw parameter. It would be unwise to create a separate function for each combination, so my first solution was to unify getter/raw param to a single structure/class that could handle both. However, this obscures the API as now I have to wrap every param with a new Wrapper(...) or a static factory method Wrp.Static(...)/.Dynamic(...). Note that there is a single, finite amount of brushes, so writing code for each is fine, however writing code for 2^N params is not preferable.

In C++ I would use the implicit constructor Wrapper(const T& t) to automatically wrap arguments to a single wrapper interface. Is there any way to solve this using generics perhaps? I know there is a fundamental difference between templates (code generation on demand) and generics (code able to handle many types), but wouldn't I be able to catch different argument types at runtime using reflection/rtti? My issue here is that I'd prefer some compile type checking and not passing object's, hoping that they actually match one of two types I expect in implementation of the wrapper.

I am looking for something that would behave like:

public void DrawShape<TBrush1, ...>(Shape sh, TBrush1 brush1, ...) 
    : where TBrush1 : Brush|Func<Brush>, ... { ... }

The main assumption here is that automatic type deduction would take place and allow me to skip the generic params. Please note that this is not a valid C# code and the imaginary | operator is the feature I'm looking for - matching two types to a single argument, possibly without any explicit user input.

0

There are 0 best solutions below