Is using function() in templates possible at all?

Alex sascha.orlov at gmail.com
Wed Apr 11 21:29:27 UTC 2018


On Wednesday, 11 April 2018 at 21:07:03 UTC, Sjoerd Nijboer wrote:

> class SortedList(T, int function(T) comparer)

I would say, alias template parameter is your friend.
https://dlang.org/spec/template.html#TemplateAliasParameter

´´´
import std.stdio;
import std.range;

void main()
{
	auto list = new SortedList!(Vector3, v => v.y)();

	assert(list.array.empty);
	list.foo(Vector3.init);
}

struct Vector3 { float x, y, z; }

class SortedList(T, alias comparer)
{
	T[] array;
	
	auto foo(T t)
	{
		for(int i = 0; i < array.length; i++)
		{
			if(comparer(this.array[i]) <=  comparer(t))
			{
				//do stuff
				array[i] = t;
			}
		}
	}
}
´´´


More information about the Digitalmars-d-learn mailing list