​原文​

public import std.complex;

public interface Mtype
{
// ...
}

public class Number : Mtype
{
public:
this(Complex!realnum=Complex!real(0,0)) shared
//加上共享
{
this.num = num;
}//也要标记为共享.
this(shared Complex!real num = cast(shared Complex!real)Complex!real(0,0))
{//加上共享
this.num.re = num.re;
this.im.re = im.re;
}//共享类,标记所有成员为共享.
Number opBinary(string op)(Number rhs) //标准opBinary
{
mixin("return new Number(this.num " ~ op ~ " rhs.num);");
}
shared(Number) opBinary(string op)(shared Number rhs) shared
{
return new shared Number(); //代码工作前的占位符.
}
package:
Complex!real num;
}

bool isMtype(T)()
{
bool ret = true;
// ...
shared T p = new shared T();
shared T p2 = new shared T();
ret &= __traits(compiles, T, p + p2);
//
return ret;
}

static assert(isMtype!Number); //失败了.

shared T c = p + p2

至​​isMtype​​​时,得到错误.如何​​有效​​​重载共享​​运算符​​​并修复它.
另,​​​__traits(compiles)​​​仅检查​​表达式​​​是否​​语义​​​正确,而不检查是否​​编译​​,这里不编译.

我加了些额外​​构造器​​​,并为​​Number​​​的​​shared​​​写了个更复杂的​​opBinary​​.现在管用了:

public import std.complex;
public import std.stdio;

public interface Mtype
{
// ...
}

public class Number : Mtype
{
public:
// 新代码开始
this()
{
this.num = Complex!real(1,1);
}
this() shared
{
this.num = Complex!real(1,1);
}
// 新代码结束
this(Complex!real num = Complex!real(0,0))
{
this.num = num;
}
this(shared Complex!real num = cast(shared Complex!real)Complex!real(0,0)) shared
{
this.num.re = num.re;
this.num.im = num.im;
}
Number opBinary(string op)(Number rhs)
{
mixin("return new Number(this.num " ~ op ~ " rhs.num);");
}
shared(Number) opBinary(string op)(shared Number rhs) shared
{//稍微改变这里代码
mixin(q{return new shared Number(Complex!real(this.num.re} ~ op ~ q{rhs.num.re, this.num.im} ~ op ~ q{rhs.num.im));}); //
}
package:
Complex!real num;
}

bool isMtype(T)()
{
bool ret = true;
// ...
shared T p = new shared T();
shared T p2 = new shared T();
ret &= __traits(compiles, T, p + p2);
return ret;
}

static assert(isMtype!Number); //成功了.

void main()
{
shared num1 = new shared Number();
shared num2 = new shared Number();
auto num3 = num1 + num2;
writeln("实: ", num3.num.re, "\n虚: ",num3.num.im);
}