struct Matrix(int row, int col){ /* ... */ }
// finds the inverse using Gauss–Jordan elimination
pure M inverse(M)(const ref M m){ /* ... */ }
Run Code Online (Sandbox Code Playgroud)
原因m是ref因为性能.显然,我不希望每次需要反转时都会复制大型矩阵,到目前为止这种方法运行良好.
但是,在编译时需要反转的情况下,它已经成为一个问题:
mixin template A(){
alias Matrix!(3, 3) Matrix3x3;
static Matrix3x3 computeSomeMatrix(){ }
immutable Matrix3x3 _m = computeSomeMatrix();
immutable Matrix3x3 _m_1 = inverse(computeSomeMatrix()); // error
}
Run Code Online (Sandbox Code Playgroud)
要修复错误,我需要更改m为非ref,但这意味着每次inverse()调用时都会复制矩阵.我该怎么办?
我看到两个选项之一。一,创建一个采用右值的版本。当函数无法使用右值时,通常会很烦人。您只需要一个简单的包装器:
pure M inverse(M)(const ref M m){ /* ... */ }
pure M inverse(M)(const M m){ inverse(m); }
Run Code Online (Sandbox Code Playgroud)
但要小心参数的常量性匹配,否则你将得到无限递归。
然而,更好的解决方案是使用auto ref. 这就是它被创建的目的。
pure M inverse(M)(const auto ref M m){ /* ... */ }
Run Code Online (Sandbox Code Playgroud)
然后,编译器将ref在适当的时候使用,在适当的时候不使用ref,而您不必担心。