[Mono-dev] Template and assignment operator in C#

Eyal Alaluf eyala at mainsoft.com
Sun Apr 30 03:56:11 EDT 2006


You can do this using interfaces without templates in C#, although you'll probably
need to work very hard to avoid the overhead of interface invoking compared to
inlinable non-virtual invokes you can do when interfaces are not involved.
If you define an interface for DoubleVec, your overload of operator+ can create an
instance of DoubleVecLazySum, etc.

Possibly, if we use generics and DoubleVecLazySum<T1,T2>, DoubleVecLazyMul<T1,T2>,
etc. are structs(and not classes), you can use generic operators like:
    DoubleVecLazySumm<T, DoubleVec> opeartor+(T x, DoubleVec y) { ... }
But in C# since all operators are tied to types you will need to repeat this exercise
for every type. E.g. inside the struct DoubleVecLazySumm<T1, T2>
    DoubleVecLazySumm<T1, DoubleVecLazySumm<T2, T3> > opeartor+(T1 x, DoubleVecLazySumm<T2, T3>  y) { ... }

Because DoubleVecLazySumm<T1, T2> (and its companions) are structs, the ExecutionEngine
will instantiate every arithmetic combination and perhaps the JIT will know how to
inline it properly. This is probably not the case today, but maybe it's a pattern that
can be developed.


On Thu, 27 Apr 2006, Rusmin Susanto wrote:

> Date: Thu, 27 Apr 2006 17:20:13 -0700 (PDT)
> From: Rusmin Susanto <rusminsusanto at yahoo.com>
> To: Mono-devel-list at lists.ximian.com
> Subject: [Mono-dev] Template and assignment operator in C#
> Hi all. I have some questions.
>  1. Is there any trick in C# similar to Expression Template in C++ to avoid pairwise evaluation?
> For example, if we have the following code in C++:
>   // DoubleVec is a class that contains a vector of double. This class has typical aritmathic operator, + - * /.
>        DoubleVec y(1000), a(1000), b(1000), c(1000),d(1000);
>        y = (a+b)/(c-d);
>  without expression template we will need 4 loops and 3 temporaries DoubleVect to process the expression as the operands are processed 2 at a time. With expression template trick in C++, we can process the expression in one hit (in one loop, no temporaries).
>  2. Is template processed at compile time or run time in C#? I know that in C++ it's processed at compile time.
>  3. I know that in C# the assignment operator '=' for object will copy the reference of rhs to the lhs.
> How about if we need to define an assignment operator for an object that needs to copy the value of member variables (not reference) of rhs to lhs?
> How do we tell C# to copy value, not reference?
>  Many thanks for your attention.
> ---------------------------------
> Talk is cheap. Use Yahoo! Messenger to make PC-to-Phone calls.  Great rates starting at 1&cent;/min.

More information about the Mono-devel-list mailing list