jdm
jdm

Reputation: 10070

Prototype for template instantiation?

I have a type VertexContainer which is a typedef'ed instantiated template:

// in a header, included into cpp
class Vertex {/*...*/};
typedef DataVector<Vertex> VertexContainer;

class SomeOtherClass;

I would like to use VertexContainer in a header, without pulling in the definition of possible. Is it possible to create a "prototype" (like a class declaration) for it?

// in header
class VertexContainer;  // <-- this doesnt work
class SomeOtherClass;

SomeHandle<SomeOtherClass> handle1;   // this works
SomeHandle<VertexContainer> handle2;  // how to prototype VertexContainer?

With GCC I get an error similar to:

error: using typedef-name 'VertexContainer' after 'class'
   class VertexContainer;
(...)
note: 'VertexContainer' has a previous declaration here
    typedef DataVector< Vertex > VertexContainer;
                                 ^~~~~~~~~~~~~~~`

Upvotes: 2

Views: 188

Answers (2)

Sam Varshavchik
Sam Varshavchik

Reputation: 118350

For an authoritative answer, you should provide more context, but in general the following will compile, if placed by itself in a header:

template<typename T> class DataVector;
class Vertex;

typedef DataVector<Vertex> VertexContainer;

You need to forward-declare both the template, and the class. However, by the time you get here:

SomeHandle<VertexContainer> handle2; 

Both the template and possibly the class (depending on how the template uses the class) will need to be fully defined. It's not possible to determine that without additional context in your question.

But, purely as a forward declaration, forward-declaring the template and the template parameter is sufficient for defining the typedef.

Furthermore:

class VertexContainer;

Your error on that line has a slightly different reason. VertexContaner is not a class. It is a typedef, an alias. A typedef does not create a new class. It creates an alias for an existing class.

Upvotes: 5

EGOrecords
EGOrecords

Reputation: 1969

Templates are just a clever way for code substitution.

So in order to be able to use a forward declaration of the type, like with any other forward declaration you are only allowed to use the type inside of the templated container in a way, that the declaration has never to be known.

So only pointers and references to your Vertex are allowed inside of DataVector, if you do not want pull in the declaration.

Upvotes: 0

Related Questions