如何处理模板类中的复合类型
How to handle composite type in a template class
我有以下模板类定义:一个典型的矩阵类 -
template<typename T>
class Matrix
{
std::vector<Array<T>> m_rows;
uint32_t m_M;
uint32_t m_N;
bool m_container;
public:
Matrix() : m_rows{}, m_M(0), m_N(0), m_container(true) { }
Matrix(uint32_t width, uint32_t height, T val, uint32_t strideX=0, uint32_t strideY=0) :
m_rows(std::max(strideY, height), Array<T>(width, T{}, strideX)),
m_M(width), m_N(height), m_container(false)
{
for(uint32_t row=0; row < height; row++)
{
m_rows[row] = val;
}
}
//more class methods, not relevant to this discussion
main(( 中的代码:
int main()
{
typedef struct { float a; float b; } MyStruct;
MyStruct val = { 1.0, 2.0 };
Matrix<MyStruct> m(3,3,val); //so, define a 3x3 matrix with 'val' struct as constant value
}
矩阵将尝试使用 T{} 条目初始化 std::vector<> 容器。
令我惊讶的是,这奏效了! 所以,我的下一个问题是,为什么 T{} 有效? 这是将文字"转换"为"T"类型的C++方法,即使"T"是复合的?
谢谢,查尔斯
这是因为您只使用MyStruct
。由于MyStruct
可以用{}
初始化,所以它可以被编译。
但是,如果您有其他无法使用默认构造函数初始化的类,则无法对其进行编译。
struct foo{};
class faa{
public:
fee(int x){}
};
在这种情况下,
Matrix<foo>
可以编译,而
Matrix<faa>
不能。
相关文章:
- 时间复杂度 当具有复合数据类型(如元组或对)时?
- 如何处理模板类中的复合类型
- H5Tget_member_type() 返回复合 HDF5 数据类型的奇怪值
- 复合类型的动态数组
- 有没有办法改变概念中的复合需求返回的类型?
- HDF5-写入/附加HDF5复合数据类型一一带有HyperSlab
- 使用GlclearBufferdata用于复合数据类型的便携式
- C 复合分配和类型转换问题
- C++ HDF5 提取复合数据类型的一个成员
- c++hdf5:如何设计易于扩展到新的复合数据类型的程序
- gcc 的 -Wconversion 是否与使用比 int 短的整数类型的复合赋值(+= 等)不兼容?
- c++amp:复合类型,用于循环,在GPU上声明
- HDF5中嵌套的复合数据类型
- 使用模板化复合类型推理实现unique_copy
- 将迭代器取消引用到映射或 C++ 中的某些其他复合类型的类型是什么
- 不同类型的复合模式重用
- 复合赋值运算符的类型/类型转换?(例如*=(星形等于))
- 隐藏复合数据类型的某些字段,使其不被写入(或从hdf5文件中读取)
- 从HDF5中读取复合数据类型的字符串
- 是否有办法在当前类中打印复合数据类型的所有属性?