Шаблоны позволяют добавлять некоторые функции в класс, но есть проблема с конструкторами: он работает только тогда, когда шаблон ctor и класс (переданный как параметр) ctor имеют форму по умолчанию. (DPaste tester)Шаблоны классов и конструкторы
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;
}
Можно ли назвать cSource2 CTOR в cSourceWithSomeStuffs2? Если нет, есть ли свойство проверить, что класс имеет конструктор по умолчанию?
Хорошо, но класс источников должен иметь хотя бы пустое значение this(), иначе компилятор произведет ошибку. Необходимо проверить наличие по умолчанию ctor. – BBasile