在 C++ 中使用 typedef 缩短模板类的非嵌套成员类的类型名 [重复]

问题描述 投票:0回答:1

编辑:有人认为这是this问题的重复。情况并非如此,因为该问题是关于“如何在模板类中使用嵌套结构/类类型作为返回值”(该问题的字面标题),而我的问题是关于两个单独的模板化类(未嵌套) 以及当这些类共享模板参数时我如何使用 typedef 来引用成员。我更改了标题,希望能更清楚地说明这一点。

在以下显示模板化矩形类的示例中:

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;

};

,模板化矩形类实现:

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) {}

,一个模板化的空间类:

template<typename CoordinateT>
class Space
{
public:
    typedef Rect<CoordinateT> rectType; // A: WORKS
    
public:
    Space();
    
public:
    rectType bounds(); // B: WORKS

};

和模板化空间类实现:

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
}

我想通过使用

typedef
来缩短 bounds() memeber 函数的返回类型的输入。

但是编译失败并显示以下消息:

“未知类型‘rectType’”

(见上面标有 C: ERROR 的行)

为什么这行不通,在这种情况下我怎么能吃蛋糕呢?

c++ class templates variables typedef
1个回答
2
投票

类外定义的声明符 id (

Space<PixelT, CoordinateT>::bounds
) 中类名之前词法上的所有内容都不会在类的范围内查找。

如果你想在类的范围内查找返回类型,在

typedef
可以找到的地方,你可以使用新式返回类型声明形式:

template<typename CoordinateT>
auto Space<PixelT, CoordinateT>::bounds() -> rectType
{ /*...*/ }

否则你需要符合

rectType
与它应该查找的类:

template<typename CoordinateT>
typename Space<PixelT, CoordinateT>::rectType Space<PixelT, CoordinateT>::bounds()
{ /*...*/ }
这里额外需要

typename
,因为
Space<PixelT, CoordinateT>
是依赖的(依赖于模板参数),所以需要告诉编译器
Space<PixelT, CoordinateT>::rectType
是类型名而不是数据成员或成员函数,编译器可以' 在模板实例化之前知道,但需要知道才能解析声明。有关详细信息,请参阅这个问题

© www.soinside.com 2019 - 2024. All rights reserved.