EDIT: Some people suggest that this is a duplicate of this question. This is NOT the case as that question is about "How to use a nested struct/class type as a return value, in a template class" (the literal title of that question) and my question is about two separate templated classes (not nested) and how I can use a typedef to refer to a member when those classes share template parameters. I have changed the title to hopefully make this more clear.
In the following example showing a templated rectangle class:
template<typename CoordinateT>
class Rect{
private:
CoordinateT x1;
CoordinateT y1;
CoordinateT x2;
CoordinateT y2;
public:
constexpr Rect() noexcept : x1(0), y1(0), x2(-1), y2(-1) {}
constexpr Rect(CoordinateT left, CoordinateT top, CoordinateT width, CoordinateT height) noexcept;
};
, the templated rectangle class implementation:
template<typename CoordinateT>
constexpr inline Rect<CoordinateT>::Rect(CoordinateT aleft, CoordinateT atop, CoordinateT awidth, CoordinateT aheight) noexcept
: x1(aleft), y1(atop), x2(aleft + awidth - 1), y2(atop + aheight - 1) {}
, a templated space class:
template<typename CoordinateT>
class Space
{
public:
typedef Rect<CoordinateT> rectType; // A: WORKS
public:
Space();
public:
rectType bounds(); // B: WORKS
};
and the templated space class implementation:
template<typename CoordinateT>
rectType Space<PixelT, CoordinateT>::bounds(){ // C: ERROR, recType not available here
// [....] calculate bounds in x1, y1, x2 ,y2
return rectType(x1,y1,x2-x1,y2-y1); // D:WORKS
}
I want to shorten my typing of the return type for the bounds()
memeber function by using a typedef.
However this fails to compile with the following message:
"Unknown type 'rectType'"
(See line marked C: ERROR above)
Why does this not work, and how can I have my cake an eat it too in this scenario?