d构的元组静态索引

原文
我想静态索引我的类:

struct Point
{
     double x;
     double y;
     alias expand = typeof(this).tupleof;
     alias expand this;
}
 unittest
 {
    Point p = Point(1.2,3.4);
    assert(p[0]==1.2);//像这样
    assert(p[1]==3.4);
    assert(!__traits(compiles,Point.init[3]));
 }

通过了,我喜欢该技术,从2.094开始,允许别名tupleof.std.typecons.Tuple的工作方式不一样.声明元组为别名本d成员,再定义名字访问器.
阿里:std.typecons.Tuple就是干这个的,可这样:

import std.typecons;

alias Point = Tuple!(double, "x", double, "y");//元组.

unittest
{
  Point p = Point(1.25,3.5);
  assert(p[0]==1.25);
  assert(p.x==1.25);
  assert(p[1]==3.5);
  assert(p.y==3.5);
  assert(!__traits(compiles,Point.init[3]));
}

void foo(ref Point p) {
  p.x += p.y;
}

unittest {
  auto p = Point(1.5, 2.75);
  p.foo();
  assert(p.x == 4.25);
  assert(p.y == 2.75);
}

void main() {
}

每一不喜欢,但元组可以:

foreach(x, y; only(Point(1.0, 2.0)) {} //错误
foreach(x, y; only(tuple(1.0, 2.0)) {} // ok

最上面,很有意思技巧,这样,不必用生成插件.

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