[英]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.