dcoder wrote:

> Suppose I have a base class with many ctors().
> 
> I want to inherit from the base class and make one slight alteration to
> it, but I don't want to write X times the following:
> 
> this(args) {
>   super(args);
> }
> 
> Does D have an easy way for the derived class to 'inherit' all or some of
> the base class ctors(), and just override/add ctors() in the derived
> class?
> 
> In Java, we can use eclipse to auto-generate code for us.  :)  But,
> the results look cluttered, and it's really not a solution.
> 
> Anyways, just curious.
> 
> thanks.

Here is a possible solution to your problem:

-Rory
import std.traits, std.conv, std.typetuple;
/** Generates constructors for a super class in one of its sub classes
 *  mixin(inheritconstructors_helper!(class, types of constructors to export)();
 */
string inheritconstructors_helper(alias T,Selectors...)() if (is (T == class)) {
	string s="";
	foreach (m; __traits(getOverloads, T, "__ctor")) {
		string args, args1;
		if (Selectors.length > 0 && staticIndexOf!(typeof(&m), Selectors)==-1) { // don't export constructors that aren't requested
			continue;
		}
		foreach (i, cons; ParameterTypeTuple!(typeof(&m))) {
			args ~= ","~cons.stringof~" v"~to!string(i); // declaration arguments
			args1 ~= ",v"~to!string(i);					// arguments for super(???) call
		}
		args = args.length < 1 ? args : args[1..$];
		args1 = args1.length < 1 ? args1 : args1[1..$];
		s ~= "this("~args~") { super("~args1~"); }\n";
	}
	return s;
}

class A {
	double myd;
	this(int x) { myd = x; }
	this(float x) { myd = x; }
	this(string s, int mul) { myd = to!double(s)*mul; }
}
class B : A {
//	mixin(inheritconstructors_helper!(A,TypeTuple!(A function(string,int),A function(int)))()); // only import the two specified constructors
//	mixin(inheritconstructors_helper!(A,void)()); // ends up as empty string
	mixin(inheritconstructors_helper!(A)()); // import all constructors from parent class
}


void main() {
	A a = new B(4);
	a = new B("42",2);
}

Reply via email to