Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What makes this "declarator invalid"? C++

Tags:

c++

gcc

templates

I have Vertex template in vertex.h. From my graph.h:

20 template<class edgeDecor, class vertexDecor, bool dir>
21 class Vertex;

which I use in my Graph template.

I've used the Vertex template successfully throughout my Graph, return pointers to Vertices, etc. Now for the first time I am trying to declare and instantiate a Vertex object, and gcc is telling me that my 'declarator' is 'invalid'. How can this be?

81 template<class edgeDecor, class vertexDecor, bool dir>
82 Graph<edgeDecor,int,dir> Graph<edgeDecor,vertexDecor,dir>::Dijkstra(vertex s, bool print = false) const
83 {
84    /* Construct new Graph with apropriate decorators */
85    Graph<edgeDecor,int,dir> span = new Graph<edgeDecor,int,dir>();
86    span.E.reserve(this->E.size());
87
88    typename Vertex<edgeDecor,int,dir> v = new Vertex(INT_MAX);
89    span.V = new vector<Vertex<edgeDecor,int,dir> >(this->V.size,v);
90 };

And gcc is saying:

graph.h: In member function ‘Graph<edgeDecor, int, dir> Graph<edgeDecor, vertexDecor, dir>::Dijkstra(Vertex<edgeDecor, vertexDecor, dir>, bool) const’:
graph.h:88: error: invalid declarator before ‘v’
graph.h:89: error: ‘v’ was not declared in this scope

I know this is probably another noob question, but I'll appreciate any help.

like image 416
Niel de Wet Avatar asked Mar 23 '10 05:03

Niel de Wet


2 Answers

Probably needs to be

Vertex<edgeDecor,int,dir> v = new Vertex(INT_MAX);

because you are declaring an instance of Vertex. typename keyword is only valid inside template parameter list.

Thanks Abhay and outis for pointing out valid uses of keyword outside the template parameter list.

After having another look at the code a number of other things come to mind:

  1. As pointed out by Mike Dinsdale you are missing template parameters here: new Vertex(INT_MAX);. Try Vertex<edgeDecor,int,dir> instead.
  2. You are assigning a pointer to a class instance. If you are creating it on the stack it should be something like this:

    Vertex v(INT_MAX);

If creating on the heap v must be pointer type:

Vertex<edgeDecor,int,dir>* v = new Vertex<edgeDecor,int,dir>(INT_MAX);
like image 71
Igor Zevaka Avatar answered Oct 14 '22 20:10

Igor Zevaka


Igor is right. As for the following error:

graph.h:88: error: expected type-specifier before ‘Vertex’ 

... you probably need to say:

Vertex<edgeDecor,int,dir> v = new Vertex<edgeDecor,int,dir>(INT_MAX);
like image 36
Agnel Kurian Avatar answered Oct 14 '22 20:10

Agnel Kurian