Forward declaration of nested types/classes in C++

If you really want to avoid #including the nasty header file in your header file, you could do this:

hpp file:

class MyClass
{
public:
    template<typename ThrowAway>
    void doesStuff();
};

cpp file

#include "MyClass.hpp"
#include "Annoying-3rd-party.hpp"

template<> void MyClass::doesStuff<This::Is::An::Embedded::Type>()
{
    // ...
}

But then:

  1. you will have to specify the embedded type at call time (especially if your function does not take any parameters of the embedded type)
  2. your function can not be virtual (because it is a template)

So, yeah, tradeoffs...


class IDontControl
{
    class Nested
    {
        Nested(int i);
    };
};

I needed a forward reference like:

class IDontControl::Nested; // But this doesn't work.

My workaround was:

class IDontControl_Nested; // Forward reference to distinct name.

Later when I could use the full definition:

#include <idontcontrol.h>

// I defined the forward ref like this:
class IDontControl_Nested : public IDontControl::Nested
{
    // Needed to make a forwarding constructor here
    IDontControl_Nested(int i) : Nested(i) { }
};

This technique would probably be more trouble than it's worth if there were complicated constructors or other special member functions that weren't inherited smoothly. I could imagine certain template magic reacting badly.

But in my very simple case, it seems to work.


You can't do it, it's a hole in the C++ language. You'll have to un-nest at least one of the nested classes.