您好,我目前正在尝试为矩阵实现模板库,因此我正在实现一些操作,例如transpose()操作。
我还希望运算符返回的矩阵(如转置)与原始矩阵共享数据。
示例:
matrix <int> x(3,3);
x.transpose() [2][1] = 42;
然后,如果我读过x[1][2]
,必须是42
。
有什么想法可以从哪里开始?
预先感谢
答案 0 :(得分:1)
以下内容:
template<class Matrix>
struct Transposed
{
Transposed(Matrix& matrix) : matrix_(matrix)
{ }
decltype(auto) operator()(int row, int col)
{
return matrix_(col, row);
}
Matrix& matrix_;
};
template<typename T>
struct Matrix
{
auto transposed()
{
return Transposed<Matrix>{*this};
}
...
};
如果您是从头开始实现矩阵,那么我不明白为什么[i][j]
语法应该比(i, j)
更易于实现。
答案 1 :(得分:-1)
我认为您可以使用转换运算符。一个简单的示例可能是:
class x {
public:
operator matrix&() { return transpose(); }
protected:
auto transpose() -> matrix & {
/* returning the matrix */
}
};