d插件模板用例

原文
如下会报错.

mixin template sum(T, R) {
   R opBinary(string op)(T rhs) const
   if (op == "+"){
      return R(x + rhs.x, y + rhs.y, z + rhs.z);
   }
}

mixin template diff(T, R) {
   R opBinary(string op)(T rhs) const
   if (op == "-") {
      return R(x - rhs.x, y - rhs.y, z - rhs.z);
   }
}

struct point{
   float x, y, z;
   mixin diff!(point, vec);
   mixin sum!(vec, point);
}

struct vec{
   float x, y, z;
}

void main(){
   point p1 = {1,2,3}, p2 = {5,6,7};
   vec v1 = p1-p2;

   vec v2 = {2,-1,0};
   point p3 = p1+v2;
}

这样也同样出错:

mixin template sumDiff(T, R){
   R opBinary(string op)(T rhs) const
   if (op == "+" || op == "-"){
      return mixin("R(x " ~ op ~ " rhs.x, y " ~ op ~ "rhs.y, z " ~ op ~ " rhs.z)");
   }
}

不用插件模板,却正常工作:

struct point{
   float x, y, z;

   vec opBinary(string op)(point rhs) const
   if (op == "-") {
      return vec(x - rhs.x, y - rhs.y, z - rhs.z);
   }

   point opBinary(string op)(vec rhs) const
   if (op == "+") {
      return point(x + rhs.x, y + rhs.y, z + rhs.z);
   }
}

struct vec{
   float x, y, z;
}

void main(){
   point p1 = {1,2,3}, p2 = {5,6,7};
   vec v1 = p1-p2;

   vec v2 = {2,-1,0};
   point p3 = p1+v2;
}

像编译器错误,因为真正方法替换插件模板代码编译得很好.
另外,删除const,否则即使修复错误,该方法也只会在const实例上使用.

mixin template sum(T, R) {
   R opBinary(string op)(T rhs) const
   if (op == "+"){
      return R(x + rhs.x, y + rhs.y, z + rhs.z);
   }
}

mixin template diff(T, R) {
   R opBinary(string op)(T rhs) const
   if (op == "-") {
      return R(x - rhs.x, y - rhs.y, z - rhs.z);
   }
}

struct point{
   float x, y, z;
   mixin diff!(point, vec);
   mixin sum!(vec, point);
}

struct vec{
   float x, y, z;
}

void main(){
   point p1 = {1,2,3}, p2 = {5,6,7};
   vec v1 = p1.opBinary!"-"(p2);   // 显式调用

   vec v2 = {2,-1,0};
   point p3 = p1.opBinary!"+"(v2);  // 显式调用
}

这似乎是编译器中的错误.可用插件模板来插件重载符号,但不能用多个插件模板.

这样管用:

mixin template both(T, R) {
   R opBinary(string op : "+")(T rhs) const
   {
      return R(x + rhs.x, y + rhs.y, z + rhs.z);
   }

   T opBinary(string op : "-")(R rhs) const
   {
      return T(x - rhs.x, y - rhs.y, z - rhs.z);
   }
}

struct point{
   float x, y, z;
   mixin both!(vec, point);
}

它也可用opBinary直接调用:

 vec v1=p1.opBinary!"-"(p2);

这是直接遗漏重载符号.应该提交错误.
它只能一个mixin模板.也不能重载类型自身.

注意,我也认为串插件可很好地工作.并且UFCS重载符号不起作用,但这是设计原因.

是的,这里有多个名,因此不会重载名字,并且类型上名会覆盖mixin模板中名.最好在类型上别名它们.

posted @   zjh6  阅读(14)  评论(0编辑  收藏  举报  
相关博文:
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 25岁的心里话
· 按钮权限的设计及实现
点击右上角即可分享
微信分享提示