views:

305

answers:

1

I have a c++ class that is very simple

struct Pt_t
{
    T x, y;
    template <class T2> operator Pt_t<T2>() { Pt_t<T2> pt = {x, y}; return pt; }
};

That allows me to create a pt that has T as any type i want. I can also do Pt_t<s8> = Pt_t<u64>; without a problem. How do i do the same in C#? i tried the below and got an error

    class Pt<T>
    {
        public T x, y;
        //between operator and <T2>, error CS1031: Type expected
        public static implicit operator<T2> Pt<T>(Pt<T2> v) {
            Pt<T> r = new Pt<T>();
            r.x = v.x;
            r.y = v.y;
            return r; 
        }
    }
+1  A: 

No, I don't think that is possible. You may have to add a method, such as To<T>.

The next problem will be "how to get from T2 to T - you can't just assign them. One option might be a conversion delegate:

public Pt<TDestination> To<TDestination>(
    Converter<T, TDestination> converter)
{
    if (converter == null) throw new ArgumentNullException("converter");
    Pt<TDestination> t = new Pt<TDestination>();
    t.x = converter(x);
    t.y = converter(y);
    return t;
}
...
var p = new Pt<int> { x = 1, y = 2 };
var p2 = p.To(t => t.ToString()); // a Pt<string>
Marc Gravell
Many thanks. I can see where to go from here. (.toShort, toUshort, all using a simple one line Converter<> or the user To(OwnConv);
acidzombie24