Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pointers of generic type?

ok so i want to make a generic class that will change the value of a datatype. The reason i want to do this is so i can have undo and redo methods. I could write a class for each valuetype i need. I.E. double, int... but it would be much easier if i could create a generic class to do this.

This is what i have

class CommandChangeDouble : Command
{
    double _previous;
    double _new;
    double* _objectRef;

    public unsafe CommandChangeDouble(double* o, double to)
    {
        _objectRef = o;
        _previous = *o;
        _new = to;
        *_objectRef = _new;
    }

    public unsafe void Undo()
    {
        *_objectRef = _previous;
    }
    public unsafe void Redo()
    {
        *_objectRef = _new;
    }
}

this is what i want

class CommandChangeValue<T> : Command
{
    T _previous;
    T _new;
    T* _objectRef;

    public unsafe CommandChangeValue(T* o, T to)
    {
        _objectRef = o;
        _previous = *o;
        _new = to;
        *_objectRef = _new;
    }

    public unsafe void Undo()
    {
        *_objectRef = _previous;
    }
    public unsafe void Redo()
    {
        *_objectRef = _new;
    }
}

but this gives me the error Error "Cannot take the address of, get the size of, or declare a pointer to a managed type ('T')"

Is there a better way to do this or a way to get around this error?

like image 537
Daniel Johnson Avatar asked Jun 17 '13 20:06

Daniel Johnson


1 Answers

C# 7.3 solved that issue with new generic constraint - unmanaged.

Basically it allows to do something like that:

void Hash<T>(T value) where T : unmanaged
{
    // Okay
    fixed (T* p = &value) 
    { 
        ...
    }
}

Docs

like image 53
Voodu Avatar answered Oct 02 '22 15:10

Voodu