开发者

Reason for not allowing forward declarations of nested class?

开发者 https://www.devze.com 2023-03-19 17:10 出处:网络
Example: // can\'t forward declare with class Foo::Bar // actual class class Foo { public: class Bar // or enum Bar

Example:

// can't forward declare with class Foo::Bar

// actual class
class Foo
{
public:
    class Bar // or enum Bar
    {
    }
};

I accept t开发者_如何学JAVAhat this is not allowed under the current C++ standards, but I couldn't come up with a good reason of not allowing it though, especially with C++0x, we're now able to forward declare enums. I would imagine an argument against it would be if we foward declare nested class which turns out to be private, it wouldn't be allowed. But this wouldn't be too different to say forward declaring a class in a namespace, and then declaring it a nested class of an outer class. The compiler would simply give an error (perhaps an error message along the line of previous declaration doesn't match this declaration).

So why is it really not allowed then?

In other words (by James McNellis), "why is class Foo::Bar; without providing a definition for Foo or Bar not allowed?"

** Given that the C++ standards committee recognised the benefit of using forward declarations to reduce dependencies and compile time by introducing forward declaration of enums in C++0x, surely this is part of the same thing isn't it?


The reason that it is not in the language is simply that nobody has come up with a good proposal on how to include it in the language. Features don't include themselves, someone has to write it up and explain the advantages and that there are no (or very minor) disadvantages.

The argument for not forward declaring enums (enum x;) was simply that the compiler cannot select the proper size for enum variables until it has seen how many values there are. This problem was solved by allowing you to decide for the compiler (enum x : int;). This has also been implemented and shown to work properly, before entering the standard.

See http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2008/n2764.pdf


Nested classes most certainly CAN be forward declared:

class Foo
{
public:
    class Bar;
};

class Foo::Bar
{
};


How could you forward declare a nested class? In order to do so, you must declaration the class that it is nested in. Once you go:

class ClassName {

You have started a full class declaration. You can't partially declare a class; it's either all here or none of it is here. So what good would be forwardly declaring the inner class if the outer class has to be fully declared?

The only reason enums couldn't be forward declared until now is because their size was determined by their enumerators. This is why you have to give them an explicit size to forward declare them.

0

精彩评论

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

关注公众号