www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - How to make a unique copy in a generic manner?

reply "Tommi" <tommitissari hotmail.com> writes:
How do you make a (deep) copy of a variable of any type? For 
example the following attempt at a generic next function doesn't 
work, because it modifies its argument if the argument is a 
reference type.

T next(T)(in T value)
     if (is(typeof(++[T.init][0]) == T))
{
     auto copy = cast(T) value;
     ++copy;
     return copy;
}

// For example, the following code outputs:
// 0
// 0
// 0
// 1

enum MyEnum
{
     first,
     second
}

struct MyStruct
{
     int m_value;
	
     ref MyStruct opUnary(string op)()
         if (op == "++")
     {
         ++m_value;
         return this;
     }
}

class MyClass
{
     int m_value;
	
     this(int value)
     {
         m_value = value;
     }
	
     ref MyClass opUnary(string op)()
         if (op == "++")
     {
         ++m_value;
         return this;
     }
}

void main(string[] args)
{
     auto intZero = 0;
     next(intZero);

     auto enumZero = MyEnum.first;
     next(enumZero);
	
     auto structZero = MyStruct(0);
     next(structZero);
	
     auto classZero = new MyClass(0);
     next(classZero);
	
     writeln(intZero);
     writeln(cast(int) enumZero);
     writeln(structZero.m_value);
     writeln(classZero.m_value);

     stdin.readln();
}
Jul 16 2012
parent Jacob Carlborg <doob me.com> writes:
On 2012-07-16 20:48, Tommi wrote:
 How do you make a (deep) copy of a variable of any type?

One way would be to serialize a value and the deserialize it. Although that would not be very efficient. https://github.com/jacob-carlborg/orange -- /Jacob Carlborg
Jul 16 2012