如何在另一个模板结构(C )中使用模板结构
how to use templated struct within another templated struct (C++)
我是C/C 的新手,并试图模板Point
和RectBound
的结构允许双重和浮点类型。
这是点定义
// simple Point structure
template <typename T, typename U, typename V>
struct Point{
T x;
U y;
V z; // optional
/*
Point(){
x = T();
y = U();
z = V();
}*/
Point(T _x, U _y) {
x = _x;
y = _y;
}
Point(T _x, U _y, V _z){
x = _x;
y = _y;
z = _z;
}
inline bool equals(Point & p){
return(p.x == x && p.y == y);
}
};
,这是直流结构
// Rectangular Bounds for tree
// T,U should hold double or float only
template <typename T, typename U, typename V>
struct RectBounds {
// x, y center point
T x;
U y;
// dimension width w and height h
T w, h;
//constructors
// (_x, _y): center of rectangle bound. (_w, _h): width and height
RectBounds(T _x, U _y, T _w, T _h){
x = _x;
y = _y;
w = _w;
h = _h;
}
// returns true if point p is in Rect bounds, false otherwise
inline bool contains(Point & p) {
float _w = w/2.0f;
float _h = h/2.0f;
return p.x >= x - _w && p.x < x + _w && p.y >= y - _h && p.y < y + _h;
}
// returns true if rectangle o intersects this, false otherwise
inline bool intersects( RectBounds & o){
float _w = w/2.0f;
float _h = h/2.0f;
return !(o.y + o.h/2.0f <= y - _h || o.y - o.h/2.0f >= y + _h || o.x + o.w/2.0f <= x - _w || o.x - o.w/2.0f >= x + _w);
}
};
我得到以下错误的错误:(从逆向倾斜函数中的返回线的错误)
)error: request for member ‘x’ in ‘p’, which is of non-class type ‘int’
error: request for member ‘x’ in ‘p’, which is of non-class type ‘int’
error: request for member ‘y’ in ‘p’, which is of non-class type ‘int’
error: request for member ‘y’ in ‘p’, which is of non-class type ‘int’
我试图在RectBounds类中定义一个点,如下所示
Point<T,U,V> cp;
,但这无济于事。
有什么建议?
首先,看来您已经使模板过度复杂化了。在Point
中,x
,y
和z
可以是不同的类型吗?我猜不是,所以您只需要一个模板参数:
template <typename T>
struct Point{
T x;
T y;
T z;
// ...
};
对于RectBounds
。
现在,您实际遇到错误的原因是由于函数contains
和intersects
的参数类型。您已经使用了Point
和RectBounds
。但是,这些名称模板,而不是 type 。功能参数需要具有类型。由于我们现在仅给出了Point
一个模板参数,因此类型可能是Point<float>
。如您所见,我们需要提供模板参数。因此以下将有效:
inline bool contains(Point<float> & p) {
但是,似乎您可能不想将其修复到某种特定类型。您要么仅接受与RectBounds
的模板参数相同类型的Point
s:
inline bool contains(Point<T> & p) {
或您希望能够使用任意类型接受Point
S,在这种情况下,您可以使contains
成为成员函数模板:
template <typename U>
inline bool contains(Point<U> & p) {
相关文章:
- 为什么在没有显式默认构造函数的情况下,将另一个结构封装在联合中作为成员的结构不能编译
- 为什么将一个结构的引用设置为等于另一个结构只会更改一个数据成员?
- 从另一个 cpp 文件更改结构内、映射键内的变量
- 如何将一个结构的字符数组复制到结构的另一个字符数组中?
- 如何将数据从一个结构链接到另一个结构
- 是否可以使用智能指针成员设置具有另一个结构的结构?
- std::transform 将一个结构数组复制到另一个结构数组
- C++将结构复制到另一个程序的资源
- 结构新手,我对如何从 void 函数中返回值并将其放入另一个函数感到困惑
- 可以访问一个类中的播放器结构,但不能访问另一个类中的播放器结构
- 如何在另一个结构中初始化结构数组?
- 在另一个结构中声明内部结构会导致错误:结构使用无效
- 通过 C++ 中的另一个结构成员访问结构
- 难以从另一个结构中的函数返回结构
- 有没有办法将一个对象注入到另一个对象的结构中?
- 如何制作一个结构程序,在其中可以存储无限量的数据,以便每次您想要时都可以将另一个产品添加到列表中?
- 将一个结构的值复制到另一个结构
- 结构C++可以用 0 初始化,但不能用另一个 int 初始化
- 如何将矢量结构从一个标头文件传递到另一个标头文件中的类
- 是否可以定义一个在外部"C"块中继承另一个结构的结构?