Virtual templates members

JS js.mdnq at gmail.com
Wed Aug 7 18:48:47 PDT 2013


The following code is used to reduce dependence on new and the 
GC. iNew is used as the replacement.

The problem is, where ever New is used, it requires typing the 
type twice.

e.g.,

A.New!A(...)

instead of A.New(...)

Is there any way to solve this issue?

(iNew is suppose to provide the contract to implement a "new" 
like method that will allocate the class. Note there is no 
virtual function so no overhead)


import std.stdio, std.conv;

enum eNew
{
	Default = 0,
}

interface iNew
{

	final static T New(T, A...)(A args)
	{
		eNew type = eNew.Default;
		static if (A.length == 0 || !is(typeof(args[0]) == eNew))
			alias nargs = args;
		else
		{
			type = cast(eNew)args[0];
			alias nargs = args[1..$];
		}

		writeln(">> ",  __traits(classInstanceSize, T));

		switch (type)
		{	
			default: return new T(nargs);
		}
		
		return new T(nargs);
	}
}

class A : iNew
{
	int t;
}

class B : A
{
	int q;
     double d;
}

void main()
{
	A a = A.New!A();
	B b = B.New!B();
	readln();
}


More information about the Digitalmars-d-learn mailing list