d使用d1的重载操作符

网友投稿 492 2022-11-26

d使用d1的重载操作符

d使用d1的重载操作符

​​原文​​

上个月发布的​​2.100​​​版本语言已完全删除​​旧重载​​​符号.但是,使用D出色的​​元编程功能​​​,可以编写​​插件模板​​​,来让​​D1​​​风格​​重载符号​​继续工作.

对比​​D1​​与​​D2​​重载符号

​​重载​​​符号用来​​自定义​​​(如+和-)操作符.在​​D1​​​中,是用​​普通命名​​​函数,如加法​​opAdd​​​或乘法​​opMul​​​.示例,用​​整​​​来表示​​内部状态​​的结构类型:

struct S { int x; S opAdd(S other) { return S(x + other.x); } S opSub(S other) { return S(x - other.x); } S opMul(S other) { return S(x * other.x); } S opDiv(S other) { assert(other.x != 0, "除零!"); return S(x / other.x); }//后面简称为`四块代码`.}void main() {//后面简写为`主块代码` S s1 = S(6); S s2 = S(3); assert(s1 + s2 == S( 9)); assert(s1 - s2 == S( 3)); assert(s1 * s2 == S(18)); assert(s1 / s2 == S( 2)); assert( s1 % s2 == S( 0)); assert((s1 | s2) == S( 7)); //...}

太多重复代码.​​D2​​改进了.

struct S { int x; S opBinary(string op)(S other) { static if(op == "/" || op == "%") assert(other.x != 0, "除零!"); return mixin("S(x ", op, " other.x)"); } }主块代码;

注意,仅有​​一个函数​​​(​​除法​​​符号​​略有​​​不同),且处理​​所有数学运算​​​!​​代码​​​更容易编写,更不容易​​出错​​​,也​​更简洁​​.

别名符号

struct S { int x; 四块代码; alias opBinary(op : "+") = opAdd; alias opBinary(op : "-") = opSub; alias opBinary(op : "*") = opMul; alias opBinary(op : "/") = opDiv;//别名符号.}

注意,在此使用了​​D元编程​​​很酷的特性.​​别名​​​是​​同名模板​​​,​​特化​​​了模板参数,并用​​模板约束​​过滤.

插件模板

mixin template D1Ops() { static if(__traits(hasMember, typeof(this), "opAdd")) alias opBinary(op : "+") = opAdd;//当有`opadd`时,别名此函数为左边.}

struct S { int x; 四块代码; mixin D1Ops;}

使用别名,可处理现有​​重载符号​​​问题.再借助​​静每一​​扩展.

mixin template D1Ops() { static foreach(op, d1; ["+" : "opAdd", "-" : "opSub", "*" : "opMul", "/" : "opDiv","%" : "opMod"]) {//static foreach编译时迭代普通运行时迭代元素. static if(__traits(hasMember, typeof(this), d1)) alias opBinary(string s : op) = mixin(d1);//对每一个操作. }}

必须别名​​opBinary​​​至​​符号​​​.而不是串,因而用​​mixin(d1)​​​.这是相对新的​​功能​​​.旧版要用​​mixin​​​在整个​​别名​​语句.最新的,相对就好看多了.最终代码:

mixin template D1Ops() { static foreach(op, d1; ["+" : "opAdd", "-" : "opSub", "*" : "opMul", "/" : "opDiv","%" : "opMod"]) { static if(__traits(hasMember, typeof(this), d1)) alias opBinary(string s : op) = mixin(d1); }}struct S { int x; 四块代码; mixin D1Ops;}主块代码;

​​opMod​​​不在​​类​​​中.​​​其他D1风格符号​​​ 可,另加​​循环​​来处理​​opUnary/opBinaryRight​​, 还可​​嵌套​​映射,或按​​映射​​部分,来包含要别名的​​模板名​​.​​opBinaryRight​​和​​opBinary​​,除了在​​in​​上外,其余相同.用​​静每一​​不易出错.

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:【语音去噪】基于matlab谱减法+维纳滤波+卡尔曼滤波语音去噪【含Matlab源码 1881期】
下一篇:带你轻松了解Modbus协议
相关文章

 发表评论

暂时没有评论,来抢沙发吧~