我认为我应该说明我对参数化矩阵维度的评论,因为您以前可能没有见过这种技术。
template<class T, size_t NRows, size_t NCols>
class Matrix
{public:
Matrix() {} // `data` gets its default constructor, which for simple types
// like `float` means uninitialized, just like C.
Matrix(const T& initialValue)
{ // extra braces omitted for brevity.
for(size_t i = 0; i < NRows; ++i)
for(size_t j = 0; j < NCols; ++j)
data[i][j] = initialValue;
}
template<class U>
Matrix(const Matrix<U, NRows, NCols>& original)
{
for(size_t i = 0; i < NRows; ++i)
for(size_t j = 0; j < NCols; ++j)
data[i][j] = T(original.data[i][j]);
}
private:
T data[NRows][NCols];
public:
// Matrix copy -- ONLY valid if dimensions match, else compile error.
template<class U>
const Matrix<T, NRows, NCols>& (const Matrix<U, NRows, NCols>& original)
{
for(size_t i = 0; i < NRows; ++i)
for(size_t j = 0; j < NCols; ++j)
data[i][j] = T(original.data[i][j]);
return *this;
}
// Feel the magic: Matrix multiply only compiles if all dimensions
// are correct.
template<class U, size_t NOutCols>
Matrix<T, NRows, NOutCols> Matrix::operator*(
const Matrix<T, NCols, NOutCols>& rhs ) const
{
Matrix<T, NRows, NOutCols> result;
for(size_t i = 0; i < NRows; ++i)
for(size_t j = 0; j < NOutCols; ++j)
{
T x = data[i][0] * T(original.data[0][j]);
for(size_t k = 1; k < NCols; ++k)
x += data[i][k] * T(original.data[k][j]);
result[i][j] = x;
}
return result;
}
};
所以你要声明一个floats 的 2x4 矩阵,初始化为 1.0,如下:
Matrix<float, 2, 4> testArray(1.0);
请注意,由于大小是固定的,因此不需要存储在堆上(即使用operator new)。您可以在堆栈上分配它。
您可以创建另外一对ints 矩阵:
Matrix<int, 2, 4> testArrayIntA(2);
Matrix<int, 4, 2> testArrayIntB(100);
对于复制,尺寸必须匹配,但类型不匹配:
Matrix<float, 2, 4> testArray2(testArrayIntA); // works
Matrix<float, 2, 4> testArray3(testArrayIntB); // compile error
// No implementation for mismatched dimensions.
testArray = testArrayIntA; // works
testArray = testArrayIntB; // compile error, same reason
乘法必须有正确的维度:
Matrix<float, 2, 2> testArrayMult(testArray * testArrayIntB); // works
Matrix<float, 4, 4> testArrayMult2(testArray * testArrayIntB); // compile error
Matrix<float, 4, 4> testArrayMult2(testArrayIntB * testArray); // works
请注意,如果有问题,它会在编译时被捕获。这只有在矩阵尺寸在编译时固定的情况下才有可能。另请注意,此边界检查导致没有额外的运行时代码。如果您只是将尺寸设为常量,则会得到相同的代码。
调整大小
如果您在编译时不知道矩阵尺寸,但必须等到运行时,此代码可能没有多大用处。您必须编写一个在内部存储维度和指向实际数据的指针的类,并且它需要在运行时完成所有操作。提示:编写operator [] 将矩阵视为重新整形的 1xN 或 Nx1 向量,并使用operator () 执行多索引访问。这是因为operator [] 只能带一个参数,而operator () 没有这个限制。尝试支持M[x][y] 语法很容易使自己陷入困境(至少迫使优化器放弃)。
也就是说,如果您需要通过某种标准矩阵调整大小来将一个 Matrix 调整为另一个,假设所有维度在编译时都是已知的,那么您可以编写一个函数来调整大小。例如,此模板函数会将任何Matrix 重塑为列向量:
template<class T, size_t NRows, size_t NCols>
Matrix<T, NRows * NCols, 1> column_vector(const Matrix<T, NRows, NCols>& original)
{ Matrix<T, NRows * NCols, 1> result;
for(size_t i = 0; i < NRows; ++i)
for(size_t j = 0; j < NCols; ++j)
result.data[i * NCols + j][0] = original.data[i][j];
// Or use the following if you want to be sure things are really optimized.
/*for(size_t i = 0; i < NRows * NCols; ++i)
static_cast<T*>(result.data)[i] = static_cast<T*>(original.data)[i];
*/
// (It could be reinterpret_cast instead of static_cast. I haven't tested
// this. Note that the optimizer may be smart enough to generate the same
// code for both versions. Test yours to be sure; if they generate the
// same code, prefer the more legible earlier version.)
return result;
}
...好吧,无论如何,我认为这是一个列向量。希望如果没有,如何解决它是显而易见的。无论如何,优化器会看到你返回result 并删除额外的复制操作,基本上是在调用者想要看到的地方构建结果。
编译时维度健全性检查
假设如果维度为0(通常导致Matrix 为空),我们希望编译器停止。我听说过一种叫做“编译时断言”的技巧,它使用模板特化并声明为:
template<bool Test> struct compiler_assert;
template<> struct compiler_assert<true> {};
它的作用是让你编写如下代码:
private:
static const compiler_assert<(NRows > 0)> test_row_count;
static const compiler_assert<(NCols > 0)> test_col_count;
基本思想是,如果条件为true,则模板将变为空的struct,没有人使用并被默默丢弃。但是如果是false,编译器就找不到struct compiler_assert<false> 的定义(仅仅一个声明,这还不够)并且会出错。 p>
更好的是 Andrei Alexandrescu 的版本(来自 his book),它允许您使用声明对象的声明名称作为即兴错误消息:
template<bool> struct CompileTimeChecker
{ CompileTimeChecker(...); };
template<> struct CompileTimeChecker<false> {};
#define STATIC_CHECK(expr, msg) { class ERROR_##msg {}; \
(void)sizeof(CompileTimeChecker<(expr)>(ERROR_##msg())); }
您为msg 填写的内容必须是有效的标识符(仅限字母、数字和下划线),但这没什么大不了的。然后我们只需将默认构造函数替换为:
Matrix()
{ // `data` gets its default constructor, which for simple types
// like `float` means uninitialized, just like C.
STATIC_CHECK(NRows > 0, NRows_Is_Zero);
STATIC_CHECK(NCols > 0, NCols_Is_Zero);
}
瞧,如果我们错误地将其中一个维度设置为0,编译器就会停止。有关它的工作原理,请参阅Andrei's book 的第 25 页。请注意,在true 的情况下,只要测试没有副作用,生成的代码就会被丢弃,因此不会出现膨胀。