d - 如何在编译时使用 'ref'?

标签 d

struct Matrix(int row, int col){ /* ... */ }

// finds the inverse using Gauss–Jordan elimination
pure M inverse(M)(const ref M m){ /* ... */ }

原因mref是因为性能。显然,我不希望每次需要逆矩阵时都复制大型矩阵,到目前为止,这种方法运行良好。

但是,在编译时需要逆的情况下,它已成为一个问题:
mixin template A(){

  alias Matrix!(3, 3) Matrix3x3;

  static Matrix3x3 computeSomeMatrix(){ }

  immutable Matrix3x3 _m = computeSomeMatrix();
  immutable Matrix3x3 _m_1 = inverse(computeSomeMatrix());  // error
}

要修复错误,我需要更改 m到非引用,但这意味着每次都会复制矩阵 inverse()叫做。我该怎么办?

最佳答案

我看到了两个选项之一。一,创建一个采用右值的版本。当函数无论如何都不能与右值一起工作时,这通常很烦人。您只需要一个简单的包装器:

pure M inverse(M)(const ref M m){ /* ... */ }
pure M inverse(M)(const M m){ inverse(m); }

但是要注意参数的常量匹配,否则你会得到无限递归。

但是,更好的解决方案是使用 auto ref .这就是它的创建目的。
pure M inverse(M)(const auto ref M m){ /* ... */ }

然后编译器将使用 ref适当且非 ref在适当的时候,您不必担心。

关于d - 如何在编译时使用 'ref'?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9083369/

相关文章:

d - 在构造函数之外初始化 const 对象

d - D中的函数命名空间问题

d - 具有不可复制类型的数组

visual-studio - 如何为 DUB 包生成 PDB 文件?

game-engine - 我的 MVP 矩阵运算有什么问题?

arrays - 如何在 D2 中初始化 const 值数组?

reflection - 枚举反射

reference-counting - 使用 RefCounted!(T) 在 D 中创建引用计数对象

templates - DMD 拒绝实例化模板 : not a template declaration

operator-overloading - D opBinary()() 重载错误?