在类型安全性的同时,初始化带有支撑的矩阵类
Initialize a matrix class with braces while being type safety
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.
相关文章:
- 为表示一个或多个操作的C++函数的int参数寻找类型安全的替换
- 附加类型安全的子类std::string
- 什么是 c/c++ 中的类型安全
- 在模板类中使用'new'类型安全吗?
- 类型安全可变参数函数
- 类型安全 - all_of/ any_of/ none_of for std::tuple
- 如何在具有模板函数的类中使用类型安全的联合(变体)
- 将自动类型变量初始化为零.这种类型安全吗?
- 在 C++ 中强制实施类型安全,而无需使用额外的类
- 用于memcpy的类型安全C 包装器
- 以更健壮和类型安全的方式处理ASCII命令
- 是否有任何类型安全的、编译时检查的 printf 的实现
- 如何在C++中使类型安全字符串"definition"对象?
- 以最新的C 的类型安全方式从枚举中随机选择元素
- 新的类型安全枚举是否定义为从 0 开始
- C++(类似SBT)的类型安全构建系统
- 初始值设定项列表引用类型安全
- 类型安全的c++11枚举类标志的模板
- valarray<valarray<内置类型> >安全吗?
- 具有按类型安全查找的可变大小异构容器