我正在尝试开发自己的 3D 渲染器,为此我需要一个 3D 矢量结构。我试图使其尽可能通用,因此我使用模板化结构。
我创建了一个Vec<size_t, typename>
为了简单起见,我将 Vec 专门化为具有 x 和 y 属性。像这样:
template <size_t DIM, typename T>
struct Vec
{
T data[DIM];
Vec() : data() {}
Vec(std::vector<T> _data)
{
assert(_data.size() == DIM);
for (int i = DIM; i--; data[i] = _data[i])
;
}
template <typename U>
Vec(Vec<DIM, U> v)
{
for (int i = 0; i < DIM; i++)
data[i] = (T)v[i];
}
T &operator[](size_t idx)
{
return data[idx];
}
};
template <size_t LEN, size_t DIM, typename T>
Vec<LEN, T> embed(Vec<DIM, T> &v, T fill = 1)
{
Vec<LEN, T> ret;
for (size_t i = LEN; i--; ret[i] = (i < DIM ? v[i] : fill))
;
return ret;
}
template <size_t LEN, size_t DIM, typename T>
Vec<LEN, T> proj(Vec<DIM, T> &v)
{
Vec<LEN, T> ret;
for (size_t i = LEN; i--; ret[i] = v[i])
;
return ret;
}
template <typename T>
struct Vec<2, T>
{
union
{
T data[2];
struct
{
T x, y;
};
};
};
typedef Vec<2, int> Vec2i;
typedef Vec<2, float> Vec2f;
typedef Vec<2, double> Vec2d;
但是当我这样做时,我收到此错误:
...
/src/main.cpp:61:62: error: no matching function for call to ‘Vec<2, int>::Vec(Vec<2, double>)’
61 | verts[i] = (Vec<2, int>)proj<2>(face.verts[i]);
| ^
...
/include/geometry.h:52:8: note: candidate: ‘Vec<2, int>::Vec()’
52 | struct Vec<2, T>
| ^~~~~~~~~
/include/geometry.h:52:8: note: candidate expects 0 arguments, 1 provided
/include/geometry.h:52:8: note: candidate: ‘constexpr Vec<2, int>::Vec(const Vec<2, int>&)’
/include/geometry.h:52:8: note: no known conversion for argument 1 from ‘Vec<2, double>’ to ‘const Vec<2, int>&’
/include/geometry.h:52:8: note: candidate: ‘constexpr Vec<2, int>::Vec(Vec<2, int>&&)’
/include/geometry.h:52:8: note: no known conversion for argument 1 from ‘Vec<2, double>’ to ‘Vec<2, int>&&’
/include/geometry.h: In instantiation of ‘Vec<LEN, T> proj(Vec<DIM, T>&) [with long unsigned int LEN = 2; long unsigned int DIM = 3; T = double]’:
/src/main.cpp:61:62: required from here
/include/geometry.h:46:34: error: no match for ‘operator[]’ (operand types are ‘Vec<2, double>’ and ‘size_t’ {aka ‘long unsigned int’})
46 | for (size_t i = LEN; i--; ret[i] = v[i])
| ~~~^
...
Vec 没有继承函数?为什么我会收到这些错误?