How to forward declare a class which is in a namespace

后端 未结 3 1814
没有蜡笔的小新
没有蜡笔的小新 2020-11-27 17:38

I am trying to use forward declarations in header files to reduce #includes used and hence reduce dependencies where users include my header file.

However, I am unab

相关标签:
3条回答
  • 2020-11-27 17:49

    For nested namespaces, since C++17, you can do

    namespace ns1::ns2::nsN
    {
      class a;
    }
    
    0 讨论(0)
  • 2020-11-27 18:06

    Apart to forward-declare the class from within its namespace (as @billz says), remember to either use (prepend) that namespace when referring to the forward-declared class, or add a using clause:

    // B.h
    namespace Y { class A; } // full declaration of
    // class A elsewhere
    
    namespace X {
        using Y::A;   // <------------- [!]
        class B {
            A* a; // Y::A
        };
    }
    

    Ref: Namespaces and Forward Class Declarations

    0 讨论(0)
  • 2020-11-27 18:07

    To forward declare class type a in a namespace ns1:

    namespace ns1
    {
        class a;
    }
    

    To forward declare a type in multiple level of namespaces:

    namespace ns1
    {
      namespace ns2
      {
        //....
         namespace nsN
         {
            class a;
         }
        //....    
      }
    }
    

    Your are using a a member of consumer which means it needs concrete type, your forward declaration won't work for this case.

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