1

模板非常适合为类添加一些功能,但构造函数存在问题:它仅在模板 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?如果没有,是否有一个特征可以测试一个类是否具有默认构造函数?

4

2 回答 2

3

您可以构建一个super调用链,转发构造函数参数:

cImplementSomeStuffs

this(A ...)(A args) // formerly this()
{
    super(args);
    // etc ...

cSourceWithSomeStuffs2

this(int a) // could be this(A ...)(args), too
{
    super(a);
    // etc ...
于 2013-08-13T12:46:13.567 回答
0

When class is inherited like this class C : Base {} or templatized like this class C (Base) : Base {}, then the default constructors is called on the Base class, if not done otherwise.

to call other that default constructor include super call in the derived constructor like:

class C : Base { super(myArguemnts); your code }

class C (Base) : Base { super(myArguemnts); your code } this can get trickier as yo don't know what type of Base will be, so you might not know what types of arguments, if any, it will accept

you can forward arbitrary augments like this if needed

this (Args...) (int a, int b, Args args) { super (args); } You can pas any number of arguments to Args.

于 2013-08-13T12:52:53.637 回答