D中的表达模板

Arl*_*len 5 d template-meta-programming

目标是实现与此C++示例相同的效果:避免创建临时对象.我试过将C++示例翻译成D而没有成功.我也尝试了不同的方法.

import std.datetime : benchmark;
import std.stdio    : writefln, writeln;

void bench(alias fun, string time = "msecs")(string msg, uint n = 1_000_000) {
  auto b = benchmark!fun(n);
  writefln(" %s: %s ms", msg, b[0].to!(time, int));
}

alias double Real;

struct Expression(string op, E1, E2) {
  E1 _v1;
  E2 _v2;
  alias _v1 v1;
  alias _v2 v2;

  auto opIndex(size_t i) {
    return mixin("v1[i]" ~ op ~ "v2[i]");
  }

  auto opBinary(string op, E)(auto ref E e) {
    return Expression!(op, typeof(this), E)(this, e);
  }
}

struct ExpVector {

  Real[40] _data = void;
  alias _data this;

  this(Real datum) pure nothrow { _data = datum; }

  auto opBinary(string op, T)(auto ref T other) {
    return Expression!(op, typeof(this), T)(this, other);
  }

  void opAssign(E)(auto ref E exp) {
    foreach(i, ref datum; _data)
      datum = exp[i];
  }
}

struct Vector {

  Real[40] _data = void;
  alias _data this;

  this(Real datum) pure nothrow { _data = datum; }

  auto opBinary(string op)(auto ref Vector other) {
    Vector ret;
    foreach(i, datum; _data)
      ret[i] = mixin("datum" ~ op ~ "other[i]");
    return ret;
  }
}

void main() {

  ExpVector e1 = ExpVector(1.5);
  ExpVector e2 = ExpVector(7.3);
  ExpVector ef;
  void T1() {
    ef = (e1 + e2) * (e1 + e2);
  }
  bench!T1(" vector operations using template expression");

  Vector v1 = Vector(1.5);
  Vector v2 = Vector(7.3);
  Vector vf;
  void T2() {
    vf = (v1 + v2) * (v1 + v2);
  }
  bench!T2(" regular vector operations");

  void T3() {
    for(int i = 0; i < vf.length; ++i)
      vf[i] = (v1[i] + v2[i]) * (v1[i] + v2[i]);
  }
  bench!T3(" what is expected if template expressions worked and temporaries were not created.");
}
Run Code Online (Sandbox Code Playgroud)

表达式模板版本比非表达式模板版本慢.我期待表达式模板版本更快,接近预期.那我的表达模板有什么问题?在D中执行表达式模板的正确方法是什么?

cyb*_*vnm 2

在维基百科的 C++ 示例中,表达式类保存对临时变量的引用,并且在表达式的情况下......

Vec a, b;
double c;
Vec result = ( a - b ) * c
Run Code Online (Sandbox Code Playgroud) ...在分配给结果向量之前,我们在内存中有某种树:
a           b
 \        /
  \      /
   \    /
 VecDifference
      \
       \
        \
       VecScaled( has copy of 'c' embedded directly in object )
Run Code Online (Sandbox Code Playgroud) VecDifference 仅保存对 a 和 b 的引用,而 VecScaled 保存对临时 VecDifference 的引用(根据 c++ 规则,该引用将一直存在,直到表达式结束)。最后,我们没有重复的初始数据,也没有不必要的计算(如果我们只使用向量的某些组件,但不是像简单赋值给 Vec 那样使用全部)
在您的结构表达式(string op,E1,E2)初始中中间数据简单地复制到数据成员,在上一个表达式的末尾,您将看到
Expression!( "*", Expression!( "-", Vec, Vec ), double )
外部表达式将具有内部表达式(“-”,Vec,Vec)和双参数的副本,内部表达式将具有a和b向量的副本。因此,在一天结束时,您避免了临时 Vec,但制作了 4 个 a 和 b 副本(不包括对结果向量的最终分配)。不过,不知道在这种情况下如何避免在 D 中进行复制。也许是指向 structres 的指针?
(顺便说一句,c ++ 11的自动类型推断和引用临时变量的表达式模板具有不幸的交互,这可能导致错误:http: //lanzkron.wordpress.com/2011/02/21/inferring-too-much/