模板非常适合为类添加一些功能,但构造函数存在问题:它仅在模板 ctor 和类(作为参数传递)ctor 具有默认形式时才有效。(DPPaste测试仪)
module main;
class cInternalMandatoryClass{};
class cImplementSomeStuffs(T): T
if((is(T==class)/* & (HaveADefaultCtor!T) */))
{
private:
cInternalMandatoryClass fObj;
public:
void Something1(){}
this(){fObj = new cInternalMandatoryClass;}
~this(){delete fObj;}
}
class cSource1
{
int fA;
this(){fA = 8;}
}
class cSource2
{
int fA;
this(){}
this(int a){fA = a;}
}
class cSourceWithSomeStuffs1: cImplementSomeStuffs!cSource1
{
this()
{
assert(fObj !is null); // check cImplementSomeStuffs ctor
assert(fA == 8); // check cSource1 ctor
}
}
class cSourceWithSomeStuffs2: cImplementSomeStuffs!cSource2
{
this(int a)
{
// need to call cSource2 ctor
assert(fObj !is null); // check cImplementSomeStuffs ctor
assert(fA == 9); // check cSource2 ctor, fails
}
}
void main(string[] args)
{
auto Foo = new cSourceWithSomeStuffs1();
delete Foo;
auto Bar = new cSourceWithSomeStuffs2(9);
delete Bar;
}
是否可以在 cSourceWithSomeStuffs2 中调用 cSource2 ctor?如果没有,是否有一个特征可以测试一个类是否具有默认构造函数?