[英]how to use templated struct within another templated struct (C++)
我是C / C ++的新手,并尝试RectBound
Point
和RectBound
的结构,以允许double和float类型。
这是Point定义
// 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);
}
};
这是RectBound结构
// 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);
}
};
我得到以下预期的错误:(来自RectBounds倾斜函数的返回行)
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,如下所示
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
。 但是,这些名称模板 ,不是类型 。 函数参数需要有类型。 由于我们现在只为Point
了一个模板参数,因此类型可能是Point<float>
。 如您所见,我们需要提供模板参数。 所以以下方法可行:
inline bool contains(Point<float> & p) {
但是,您可能不希望将其修复为某种特定类型。 要么你想只接受Point
具有相同类型作为模板参数s中RectBounds
:
inline bool contains(Point<T> & p) {
或者您希望能够接受任意类型的Point
,在这种情况下,您可以contains
一个成员函数模板:
template <typename U>
inline bool contains(Point<U> & p) {
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.