www.digitalmars.com         C & C++   DMDScript  

digitalmars.D - How about a few handy templates regarding reference/value types?


I was wondering, how about adding a few more declarations to std.traits?

As of right now, it's a bit difficult to instantiate a template parameter -- we
first have to know whether it's
a reference type or a value type in order to know whether to say `new T(...)`
or just `T(...)`. I think putting
the code below in std.traits would be very helpful in solving this problem.

Any suggestions/comments/ideas?


private import std.traits;

template isRefType(T) { enum isRefType = !is(T == delegate) && !is(typeof(*new
T()) == T); }
template RefType(T)
	static if (isRefType!(T)) alias T RefType;
	else alias T* RefType;

T instantiate(T, TParams...)(auto ref TParams params) if (is(T == delegate) ||
is(typeof(new T(params))))
	static if (isRefType!(T)) { return new T(params); }
	else static if (is(typeof(T(params)) == T)) { return T(params); }
	else { return T.init; }

	union TestUnion { }
	static assert(is(typeof(instantiate!(TestUnion)()) == TestUnion)); //unions
are value types
	static assert(is(typeof(instantiate!(Interface)()) == Interface)); //structs
are value types (Interface
is a struct in object.d)
	static assert(is(typeof(instantiate!(int)()) == int)); //primitive types are
value types
	static assert(is(typeof(instantiate!(int function(int))()) == int
function(int))); //functions are
value types
	static assert(is(typeof(instantiate!(int delegate(int))()) == int
delegate(int))); //delegates are
value types

	static assert(is(typeof(instantiate!(int[])(size_t.init)))); //arrays are
value types
	static assert(is(typeof(instantiate!(Object)()) == Object)); //Objects are
reference types
	static assert(isRefType!(Object.Monitor)); //Interface are reference types,
but can't be instantiated
May 31 2011