开发者

gcc returns error with nested class

I am attempting to use the fully qualified name of my nested class as below, but the compiler is balking!

template <class T> class Apple {
    //constructors, members, whatevers, etc...
public:
    class Banana {
    public:
        Banana() {
            //etc...
        }
        //other constructors, members, etc...
    };
};

template <class K> class Carrot{
public:
    //etc...
    void problemFunction()
    {
        Apple<int>::Banana freshBanana = someVar.returnsABanana(); //line 85
        giveMonkey(freshBanana);  //line 86
    }
};

My issue is, the compiler says:

Carrot.h:85: error: expected ';' before 'freshBanana'
Carrot.h:86: error: 'freshBanana' was not declared in this scope

I had thought that using the fully qualified name permitted me to access this nested class? It's probably going to smack me in开发者_如何学JAVA the face, but what on earth am I not seeing here??


That's probably not what you do in your code. The error message looks like you do this

Apple<K>::Banana freshBanana = someVar.returnsABanana();

The compiler has to know before it parses the code whether a name names a type or not. In this case, when it parses, it cannot know because what type K is, is not yet known (you could have a specialization for Apple<int> that doesn't have that nested class). So it assumes Apple<K>::Banana is not a type. But then, it is an expression and an operator is needed after it or a semicolon.

You can fix it by inserting typename:

typename Apple<K>::Banana freshBanana = someVar.returnsABanana();

That asserts the name is a type, and the compiler then knows to parse this as a declaration.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜