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;
}
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.
精彩评论