如何处理模板类中的复合类型

How to handle composite type in a template class

本文关键字:复合 类型 何处理 处理      更新时间:2023-10-16

我有以下模板类定义:一个典型的矩阵类 -

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>

不能。