www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - Template mixin can not introduce overloads

reply "Tofu Ninja" <emmons0 purdue.edu> writes:
Is this intended or is it a bug?

void main(string[] args)
{
	Test a;
	a.foo(5); // Fails to compile
}

struct Test
{
	mixin testMix;
	void foo(string y){}
}

mixin template testMix()
{
	void foo(int x){}
}
Jun 24 2015
parent reply "Adam D. Ruppe" <destructionator gmail.com> writes:
On Thursday, 25 June 2015 at 03:49:04 UTC, Tofu Ninja wrote:
 Is this intended or is it a bug?
Intended, the mixin template works on the basis of names. This means that you can override methods from the mixin by writing a member with the same name - very useful thing - but also means no overloading happens without an extra step. The extra step is easy though: alias the name in: void main(string[] args) { Test a; a.foo(5); // works! a.foo("4qsda"); } struct Test { mixin testMix tm; // give it a name to reference later void foo(string y){} alias tm.foo foo; // alias the mixin thing too } mixin template testMix() { void foo(int x){} } By adding that explicit alias, it tells the compiler that yes, you do want it added to the set, not completely overridden by your replacement method.
Jun 24 2015
parent "SimonN" <eiderdaus gmail.com> writes:
 On Thursday, 25 June 2015 at 03:49:04 UTC, Tofu Ninja wrote:
 Is this intended or is it a bug?
On Thursday, 25 June 2015 at 03:53:58 UTC, Adam D. Ruppe wrote:
 Intended, the mixin template works on the basis of names. This 
 The extra step is easy though: alias the name in:
I would like to to this with constructors instead of normal methods. I have tried to mix in a constructor as follows: import std.stdio; mixin template MyConstructor() { this(int x, float y) { writefln("%d, %f", x, y); } } class Base { mixin MyConstructor my_ctor; this(string s) { writefln(s); } alias my_ctor this; } void main() { Base b = new Base(3, 4.5); } $ ./mixinctor.d ./mixinctor.d(17): Error: constructor mixinctor.Base.this (string s) is not callable using argument types (int, double) Failed: ["dmd", "-v", "-o-", "./mixinctor.d", "-I."] Doing it with alias this = my_ctor; errors out too, and demands me to use alias my_ctor this; as in the original code. Can I get this to work at all? Or does alias this (for multiple subtyping) fundamentally clash here with alias my_ctor this? -- Simon
Jun 30 2015