Search code examples
c++scopenested-class

Shorter scope resolutions for private nested classes


I have this (simplified) situation:

class Tree {
    class Iterator {
        class Stack {
            // ...
        }
    public:
        // ...
    }
public:
    //...
}

I don't want to clutter the classes' definitions and I decide to write only method declarations inside classes themselves. Later on (waaay down below) when I want to define, say, copy assignment operator like this:

Tree::Iterator::Stack& Tree::Iterator::Stack::operator = (const Stack& p_stack) {
// ...
}

I have to deal with these nasty scope resolutions. I'm wondering if there's a way to shorten them, because using and typedef, as I know them, don't offer me anything.

EDIT: Since this is not CodeReview, and @Yulian requested clarification, here's the short version:

I'm making an iterative Red-Black Tree implementation. Mentioned class Iterator is for post-order traversing (so it's post-order-specific), and class Stack is its utility class. In this short program, only class Tree uses the Iterator, and only Iterator uses Stack.

After @Yulian's reminder, I recalled that it would be way more object-oriented if the mentioned classes were separately defined (maybe even as templates), but this is a small, self contained program and I'm trying to keep it that way.

EDIT: Self-contained also means that it's an isolated, single-file program, so no .h files or external code re-using whatsoever. Why? Because ACADEMIA (and associated arbitrary restrictions).


Solution

  • You could totally eliminate scopes resolutions with a using or typedef. But not with the traditional way because your nested classes are declared private. So you would have to use additional using in the public section of each nested class to "expose" them. Unfortunately, this breaks the "privateness" of them:

    class Tree {
        class Iterator {
            class Stack {
                Stack& operator = (const Stack& p_stack);
            };
        public:
          using Stack_Out = Stack;
    
            // ...
        };
    public:
        using Iterator_Out = Iterator::Stack_Out;
        //...
    
    };
    
    using Stack = Tree::Iterator_Out;
    
    Stack& Stack::operator = (const Stack& p_stack) {
    // ...
    }
    

    LIVE DEMO

    You could however, remove scope levels (except for the outer one, i.e., Tree::) with out exposing the private nested classes in the following way:

    class Tree {
        class Iterator {
            friend class Tree;
            ^^^^^^^^^^^^^^^^^^
            class Stack {
                Stack operator = (const Stack& p_stack);
            };
        public:
    
            // ...
        };
    
        using Stack = Iterator::Stack;
        ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    
    public:
    
    }; 
    
    Tree::Stack Tree::Stack::operator = (const Stack& p_stack) {
    ^^^^^^^^^^^ ^^^^^^^^^^^
    }
    

    LIVE DEMO