Sergey L.
Sergey L.

Reputation: 22562

C++ export template implementation of incomplete type

I have the following scenario:

header.h:

class A
{
    public:

    class B; // incomplete type

private:
    // is never used outside of source file for A
    std::vector<B> vector_of_bs; // template
}

source1.cpp:

class A::B {}; // defined here

All is good until here. Now if I want to use class A elsewhere it doesn't work:

source2.cpp: uses class A and doesn't compile with

vector(721): error C2036: 'A::B *' : unknown size

while compiling class template member function 'std::vector<_Ty> &std::vector<_Ty>::operator =(const std::vector<_Ty> &)'

in VS2010. How can I link against the template specialisation of std::vector in source1.o?

I also need to use this with declspec(_dllimport)...

Upvotes: 1

Views: 194

Answers (1)

juanchopanza
juanchopanza

Reputation: 227608

Standard library containers cannot be instantiated with incomplete types. To do so is undefined behaviour, and in your case produces a clear error. Other implementations would silently accept your code.

To address this issue, boost provides counterparts for the standard library containers that can in fact be instantiated with incomplete types. You could replace std::vector with the boost counterpart to fix your code:

#include <boost/container/vector.hpp>

class A
{
 public: 
    class B; // incomplete type

 private:
    boost::vector<B> vector_of_bs;
};

Upvotes: 2

Related Questions