gpt4 book ai didi

c++ - 从父模板类转换为子模板类

转载 作者:行者123 更新时间:2023-11-27 23:42:57 25 4
gpt4 key购买 nike

我有一个基本模板类。

template <typename T, int width>
struct mat

派生模板类之一是

template <typename T>
struct mat4 : public mat<T, 4>

但是当我尝试将两个矩阵相乘并赋值时

mat4<float> model(1.0f);
mat4<float> model2(1.0f);
mat4<float> a = model * model2;

我收到错误 C2440:“正在初始化”:无法从“maths::mat”转换为“maths::mat4”。我如何告诉编译器 mat4<T>mat<T,4>彼此相等吗?因为到目前为止,它们被解释为不同的类型,这阻止了赋值运算符的工作,因为它无法从 mat<T, 4> 转换。至 mat4<T>

有关我的实现的其他信息:

运算符=

template<typename T, int width>
inline mat<T, width>& mat<T, width>::operator=(const mat<T, width>& rhs)
{
*this = rhs;
}

运营商*

template<typename T, int width>
inline mat<T, width> mat<T, width>::operator*(const mat<T, width>& rhs)const{
mat<T, width> ans;

for (int y = 0; y < width; y++)
{
for (int x = 0; x < width; x++) {
T elementSum = T(0);
for (int f = 0; f < width; f++) {
elementSum += elements[x + f * width] * rhs.elements[f + y * width];
}
ans.elements[x + y * width] = elementSum;
}
}
return ans;

mat4构造函数

mat4(const T scalar = T())
:mat<T, 4>{ scalar }
{};

垫子构造器

template<typename T, int width>
inline mat<T, width>::mat(const T scalar)
{
for (int i = 0; i < cells; i++)
((i % (width+1)) == 0) ? (elements[i] = (T)1 * scalar)
: (elements[i] = (T)0);
}

最佳答案

您需要向 mat4 添加一个转换构造函数接受 mat :

template <typename T>
mat4<T>::mat4(const mat<T, 4> &that)
: mat<T, 4>(that) { }

请注意 mat4<float> a = model * model2;语句实际上并没有使用赋值运算符,尽管它在语法上存在。相反 copy initialization使用可用的非显式构造函数之一发生。

关于c++ - 从父模板类转换为子模板类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53036315/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com