在类型安全性的同时,初始化带有支撑的矩阵类



fi具有矩阵类的下一个模板:

template<typename T, int rows, int cols>
struct Matrix{
public:
    Matrix() {
        if (rows == cols)
            LoadIdentity();
    }
    T data[rows][cols];
    void LoadIdentity(){ }
    /* more methods ...  */
}
template<int rows, int cols>
using matrixf = Matrix<float, rows, cols>;
template<int rows, int cols>
using matrixd = Matrix<double, rows, cols>;

我希望能够像:

一样初始化此类
void main(){
    matrixf<2, 3> m2x3 = { { 1, 2, 3 }, {4, 5, 6} };
}

如果我尝试过,编译器说:

e0289没有构造函数的实例" vian :: matrix [with t = float,lows = 2,cols = 3]"匹配参数列表

如果我删除了默认构造函数,我会得到想要的行为,但是我失去了拥有任何构造函数的能力。

Matrix() { ... } // If I remove this, I have the behaviour I want

我发现的一种解决方案是创建一个构造函数,该构造函数将 std :: prinitizer_list >创建,但是如果我这样做,则编译器不会检查初始列表是否具有适当的矩阵参数nxm大小。

编辑:添加了加载定位方法,以便编译。

我能做的最好的是实现 @jarod42建议的内容。创建一个像他描述的方式一样:

Matrix(std::array<std::array<T, cols>, rows>)怎么样?-jarod42

即使它不做我想要的。我将其作为答案,因为它比我在之前(拥有std :: prinistizer_list的构造函数)更安全。它可以确保您不会通过比预定的更多参数,而是允许您更少的指定。例如

matrixf<2, 3> m2x3{ {1, 2, 3, 4, 5, 6} }; // this compiles.
matrixf<2, 3> m2x3{ {1, 2, 3, 4} }; // this also compiles. Missing values are automatically set to 0.

这种方法的缺点是语法。我想通过用以下卷发来描述每一行来初始化我的矩阵类。

matrixf<2, 3> m2x3{ {1, 2, 3}, {4, 5, 6} }; // this does not compile.
matrixf<2, 3> m2x3{ { {1, 2, 3}, {4, 5, 6} } }; // this does not compile.

最新更新