Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Templates in C#

Tags:

c#

templates

I know generics are in C# to fulfill a role similar to C++ templates but I really need a way to generate some code at compile time - in this particular situation it would be very easy to solve the problem with C++ templates.

Does anyone know of any alternatives? Perhaps a VS plug-in that preprocesses the code or something like that? It doesn't need to be very sophisticated, I just need to generate some methods at compile time.

Here's a very simplified example in C++ (note that this method would be called inside a tight loop with various conditions instead of just "Advanced" and those conditions would change only once per frame - using if's would be too slow and writing all the alternative methods by hand would be impossible to maintain). Also note that performance is very important and that's why I need this to be generated at compile time.

template <bool Advanced>
int TraceRay( Ray r )
{
    do
    {
        if ( WalkAndTestCollision( r ) )
        {
            if ( Advanced )
                return AdvancedShade( collision );
            else
                return SimpleShade( collision );
        }
    }
    while ( InsideScene( r ) );
}
like image 813
John Doe Avatar asked May 04 '10 21:05

John Doe


1 Answers

You can use T4.

EDIT: In your example, you can use a simple bool parameter.

like image 95
SLaks Avatar answered Sep 28 '22 07:09

SLaks