从陌生模板类型转换
Conversion from strange template type
本文关键字:类型转换 更新时间:2023-10-16
我有一些向量(数学类型)实现为结构体。有一个基本的Vector
,它是一个模板,然后是这个模板的多个实现,用于不同维度的向量:
template<unsigned int D>
struct Vector
{
float values[D];
inline Vector<D> operator*(const Vector<D>& v) const
{
Vector<D> result;
for (unsigned int i = 0; i < D; i++)
result[i] = values[i] * v[i];
return result;
}
float operator[](unsigned int i) const
{
return values[i];
}
};
我只包含了一个操作符,但显然还有其他的和各种方法来取点积等。然后我有这样的实现:
struct Vector2 : Vector<2>
{
Vector2(float x = 0, float y = 0) : Vector<2>()
{ }
};
然后我有两个Vector2
,我试图对它们使用乘法运算符:Vector2 textureOffsetPixels = textureOffset * textureSampleSize;
抛出错误:conversion from Vector<2u> to non-scalar type 'Vector2' requested
。什么是Vector<2u>
,为什么这不起作用?这两个变量的显式类型为Vector2
。
为了能够将textureOffset * textureSampleSize
的结果(即Vector<2>
)转换为Vector2
,您需要一个转换函数。这样的构造函数就足够了:
Vector2(const Vector<2> &base) : Vector<2>(base) {}
错误提到Vector<2u>
,因为模板参数是unsigned int
,所以2
被隐式转换为2u
。
您的operator *
返回Vector<2>
,而不是Vector2
。下面的命令可以工作:
Vector<2> a, b, c;
c = a * b;
相关文章:
- 有关插入适配器的错误。[错误]请求从 'back_insert_iterator<vector<>>' 类型转换为非标量类型
- 处理小于cpu数据总线的数据类型.(c++转换为机器代码)
- C++中的双指针类型转换
- 逐位操作的隐式类型转换
- 模板中的类型转换
- 在 C++(和 C)中进行类型转换时明显不一致
- 字符类型转换不兼容
- 将复杂的非基元C++数据类型转换为 Erlang/Elixir 格式,以使用 NIF 导出方法
- C++:用户定义的显式类型转换函数错误
- 将类指针类型转换为键时出错
- 通过引用传递参数时C++类型转换
- 在 C++ 中将一个模板类型的对象类型转换为另一个模板类型
- C++显式类型转换(C 样式强制转换)的强制表示法和static_cast的多种解释
- C++无效的函数类型转换
- 在将派生类指针类型转换为派生类指针后,从基类指针调用派生类函数
- 如何将Windows产品类型转换为名称?
- 通过构造函数方法输出的类到类类型转换是 5500 为什么不是 5555
- 事件系统:使用类型转换或联合进行继承
- 如何在参数中定义隐式类型转换的构造函数?
- 类模板实例化中的类型转换