Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

forward declaration of classes as template arguments

I always known that in C++ you can only use forward declared classes with reference or pointer. Why if I use the forward declared class below as the template argument of std::vector I don't have any problem during compiling?

Thanks

AFG

 // MyFile.hpp
 class OutClass{
 public:
      class InnClass;
      OutClass();
      void print();

      // why this doesn't create compile time
      std::vector< InnClass > m_data;
 };


 // MyFile.cpp
 class OutClass::InnClass{
 public:
      InnClass() : m_ciao(0) {}
      int m_data;
 };


 OutClass::OutClass()
 : m_data(){
        InnClass a, b;
       a.m_ciao=1; b.m_ciao=2;
        m_data.push_back( a );
        m_data.push_back( b );
 }

 void OutClass::print(){
      std::cout << m_data[0].m_ciao << std::endl;
      std::cout << m_data[1].m_ciao << std::endl;
 }


 int main( int argc, char** argv ){
      OutClass outObj;
      outObj.print();
      return 0;
 }
like image 258
Abruzzo Forte e Gentile Avatar asked Oct 11 '22 17:10

Abruzzo Forte e Gentile


1 Answers

Because maybe the specific implementation of std::vector on your platform doesn't need T to be a complete type. This is relatively easy to do for a vector, as it basically only consists of pointers and as such doesn't need a complete type if done right. However, afaik the standard demands T to be a complete type for a std::vector. So, don't rely on that.

like image 127
Xeo Avatar answered Oct 27 '22 09:10

Xeo