Function Templates and Overloading

Tom S h3r3tic at remove.mat.uni.torun.pl
Mon Jul 3 18:00:41 PDT 2006


leoandru wrote:
> correction: I'm using dmd 0.161 not 0.61 as stated.
> 
> was reading on template specialization
> http://www.digitalmars.com/d/template.html but the solution seem too cumbersome
> for what I'm trying to do, which is to have a few function templates that
> behaves just like their overloaded non-template counterparts. can that be done?

It can't be done in the obvious way... You might try something like this...


import std.stdio;


void main()
{
	Foo!(int) foo = new Foo!(int)(1,2,3,4,5,6,7);

	sort(foo); //sort natural ordering
	sort(foo, (int a, int b) { return -(a - b); } );  //sort reverse order
}

class Foo (T)
{
	alias T myT;
	this(T[] args ...)
	{
	}
}


template sortT(T) {
	void sortT (Foo!(T) foo)
	{
	// ...
	}


	void sortT (Foo!(T) foo, int delegate(T a, T b) compare)
	{
	// ...
	}


	void sortT (Foo!(T) foo, int function(T a, T b) compare)
	{
	// ...
	}
}


void sort(T, X=void*)(T foo, X compare = null) {
	static assert (is(T : Foo!(T.myT)));

	static if (!is(X == void*)) {
		return sortT!(T.myT).sortT(foo, compare);
	} else {
		return sortT!(T.myT).sortT(foo);
	}
}


... or a variation of it. The IsExpression can be invaluable at times 
and I'm sure you can make the above code look nicer. Mine's just a quick 
hack ;)


-- 
Tomasz Stachowiak  /+ a.k.a. h3r3tic +/



More information about the Digitalmars-d-learn mailing list