Drax Drax - 22 days ago 7
C++ Question

Why can't we declare a namespace within a class?

Declaring a class within a class is valid. (Nested classes)

Declaring a namespace within a class is invalid.

The question is: is there any good reason (other than c++ grammar/syntax problems) to forbid the declaration of a namespace within a class ?




As for why would i want to do that, here is an exemple :

Let's have a basic delcaration of a binary tree container

template<typename Data>
class binary_tree
{
public:
... stuff ....

private:
... iterators class declaration ...

public:
typedef left_depth_iterator_impl left_depth_iterator;
typedef right_depth_iterator_impl right_depth_iterator;
typedef left_breadth_iterator_impl left_breadth_iterator;
typedef right_breadth_iterator_impl right_breadth_iterator;

... stuff ....

private:
Data data;
binary_tree* left;
binary_tree* right;
};


Now i notice that there are a lot of iterators in my class, so i would like to regroup them within the same namespace like this :

template<typename Data>
class binary_tree
{
public:
... stuff ....

private:
... iterators class declaration ...

public:
namespace iterator
{
typedef left_depth_iterator_impl left_depth;
typedef right_depth_iterator_impl right_depth;
typedef left_breadth_iterator_impl left_breadth;
typedef right_breadth_iterator_impl right_breadth;
}

... stuff ....

private:
Data data;
binary_tree* left;
binary_tree* right;
};


This would allow a simple usage :

void function()
{
binary_tree::iterator::left_depth it;

...stuff...
}


This works if i use a class instead of a namespace, but i am then forced to declare a class that will never be instantiated which is quite a namespace.

Why allow nested classes and forbid nested namespaces within classes ? is it historical ?




Answers with semantic reasons that do not only quote part of the standard(especially syntax parts) will be apreciated :)

Answer

There's no real advantage to adding such a feature to the language. Features generally don't get added unless there's demand.

What would namespaces inside classes buy you? Would you really rather say binary_tree::iterator::left_depth instead of simply binary_tree::left_depth? Perhaps if you had multiple namespaces inside, you use them to distinguish say binary_tree::depth_iterator::left and binary_tree::breadth_iterator::right.

In any event, you can achieve the desired result using internal classes as a poor-programmer's namespace, which is even more reason why there isn't demand for true namespaces inside classes.