Equivalents to policy classes in D

Joseph Rushton Wakeling joseph.wakeling at webdrake.net
Thu Apr 19 19:36:37 PDT 2012


On 03/04/12 02:24, Cristi Cobzarenco wrote:
> Mixins templates would be the answer:

OK, I've had a go at writing up some mixin template-based policy code of my own.

However ... it winds up with compilation errors that I can't decipher:

   mixin.d(55): Error: type MyStruct!(ulong,GenOne,WriteOne) has no value
   mixin.d(56): Error: type MyStruct!(double,GenOne,WriteTwo) has no value
   mixin.d(57): Error: type MyStruct!(double,GenThree,WriteOne) has no value
   mixin.d(58): Error: type MyStruct!(long,GenThree,WriteTwo) has no value
   /usr/local/include/d2/std/conv.d(244): Error: template std.conv.toImpl does 
not match any function template declaration
   /usr/local/include/d2/std/conv.d(252): Error: template std.conv.toImpl cannot 
deduce template function from argument types !(string)(ubyte)
   /usr/local/include/d2/std/conv.d(244): Error: template instance 
toImpl!(string) errors instantiating template


Here's the code.  What am I doing wrong ... ?

/////////////////////////////////////////////////////////////////////////////////
import std.stdio;

mixin template GenOne(T)
{
	void generate()
	{
		foreach(size_t i, ref T x; this.array)
			x = i;
	}
}

mixin template GenThree(T)
{
	void generate()
	{
		foreach(size_t i, ref T x; this.array)
			x = 3*i;
	}
}

mixin template WriteOne(T)
{
	void myWrite()
	{
		foreach(T x; this.array)
			writeln(x);
	}
}

mixin template WriteTwo(T)
{
	void myWrite()
	{
		foreach(T x; this.array)
			writeln(2*x);
	}
}

struct MyStruct(T, alias GeneratePolicy, alias WritePolicy)
{
	private T[] array;

	this(size_t n)
	{
		array.length = n;
		generate;
	}

	mixin GeneratePolicy!T;
	mixin WritePolicy!T;
}

void main()
{
	auto oneOne = MyStruct!(size_t, GenOne, WriteOne);
	auto oneTwo = MyStruct!(double, GenOne, WriteTwo);
	auto threeOne = MyStruct!(double, GenThree, WriteOne);
	auto threeTwo = MyStruct!(long, GenThree, WriteTwo);

	oneOne.myWrite;
	writeln;
	oneTwo.myWrite;
	writeln;
	threeOne.myWrite;
	writeln;
	threeTwo.myWrite;
	writeln;
}

/////////////////////////////////////////////////////////////////////////////////


More information about the Digitalmars-d-learn mailing list