错误:模板类中嵌套类中的嵌套类“不是类型”

时间:2016-05-03 11:06:58

标签: c++ class templates g++ mingw

我带来了3个版本的代码,第一个导致编译错误,第二个和第三个编译成功。

代码1:

我创建的类BottomMiddle中的嵌套类,它是模板类Top中的嵌套类

template <class>
struct Top {
    struct Middle {
        struct Bottom {};
    };
    void useclass(Middle::Bottom);
};

此代码出错:

main.cpp:6:27: error: 'Top::Middle::Bottom' is not a type
 void useclass(Middle::Bottom);
                       ^

代码2:

与代码1类似,但Top是普通类(非模板)

struct Top {
    struct Middle {
        struct Bottom {};
    };
    void useclass(Middle::Bottom);
};

此代码编译成功,没有任何错误

代码3:

与代码1相似,但方法useclass采用Middle代替Bottom

template <class>
struct Top {
    struct Middle {
        struct Bottom {};
    };
    void useclass(Middle);
};

此代码也已成功编译

请告诉我:

  • 为什么无法编译代码1,哪个C ++规则阻止编译?

  • 有没有办法在模板类的嵌套类中使用嵌套类,如Bottom作为类型?

1 个答案:

答案 0 :(得分:1)

我刚刚解决了这个问题,我需要在代码1中的typename之前放置Middle::Bottom,然后才能成功编译。

template <class>
struct Top {
    struct Middle {
        struct Bottom {};
    };
    void useclass(typename Middle::Bottom);
};

P.S。我仍然希望得到更多细节的答案,例如:为什么编译器无法将Middle::Bottom识别为没有关键字typename的类型?