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
最上面,很有意思技巧,这样,不必用生成插件.
 
                
            
         浙公网安备 33010602011771号
浙公网安备 33010602011771号