struct Matrix(int row, int col){ /* ... */ }
// finds the inverse using Gauss–Jordan elimination
pure M inverse(M)(const ref M m){ /* ... */ }
原因
m
是 ref
是因为性能。显然,我不希望每次需要逆矩阵时都复制大型矩阵,到目前为止,这种方法运行良好。但是,在编译时需要逆的情况下,它已成为一个问题:
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/