How to make a unique copy in a generic manner?

Tommi tommitissari at hotmail.com
Mon Jul 16 11:48:22 PDT 2012


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();
}


More information about the Digitalmars-d-learn mailing list