Factoring out common ctor code with const members
Neil Vice
psgdg at swiftdsl.com.au
Mon Mar 10 07:53:09 PDT 2008
Just thought I'd post regarding a curiosity with constructors and const
members (2.012).
Const members can only be initialised from within constructors, not by
methods called by constructors. Passing const members into methods as out
parameters causes them to be typed 'const' and as such not assignable. All
this makes it rather difficult to factor out common constructor code in the
case where one constructor cannot simply call the other.
What apprently does work is passing inline delegates to a method that assign
to the members e.g.
class Test : Parent
{
const int member;
public this(string path)
{
super(path);
init(delegate(in int value) { member = value; } );
}
public this(Parent copy)
{
super(copy);
init(delegate(in int value) { member = value; } );
}
protected void init(void delegate(in int) assign)
{
// Realistically something based on a member of Parent
// and much longer, otherwise what's the point? =)
assign(0);
}
}
Ugly? Yes; and yet...
More information about the Digitalmars-d
mailing list