Forward declaration of nested types/classes in C++

前端 未结 7 1102
刺人心
刺人心 2020-11-22 10:45

I recently got stuck in a situation like this:

class A
{
public:
    typedef struct/class {...} B;
...
    C::D *someField;
}

class C
{
public:
    typedef          


        
相关标签:
7条回答
  • 2020-11-22 11:24
    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.

    0 讨论(0)
提交回复
热议问题