Friend function defined in class template is not in scope

M

Mike

I ran into a problem when trying to write a template class to represent
graphs.
I define function add_edge in the body of template class graph as a
friend of the class.
Unfortunately I am getting "'add_edge' was not declared in this scope"
error message at compile time.
See code below. I am using gcc version 4.2.1.
Any idea why it happens and how to fix it?

Thanks,

Mike

#include <list>
using namespace std;

template<typename VERTEX /*Vertex Satellite data*/, typename EDGE=string
/*Edge Satellite data*/>
struct graph
{

struct EDGE_LIST
{
list said:
>::iterator> > edges;
};

typedef list said:
>::iterator> > edge_list;
typedef typename edge_list::iterator edge_pointer;

typedef list<pair<VERTEX, EDGE_LIST> > vertex_list;

typedef typename vertex_list::iterator vertex_pointer;

vertex_list V;

friend edge_list& edges(vertex_pointer p){return p->second.edges;}

vertex_pointer add_vertex(VERTEX v)
{
V.push_back(make_pair(v, EDGE_LIST()));
vertex_pointer p = V.end();
return --p;
}

friend edge_pointer add_edge(vertex_pointer from, vertex_pointer
to, const EDGE& e=EDGE())
{
edges(from).push_back(make_pair(e,to));
edge_pointer p = edges(from).end();
return --p;
}

};


int main()
{
graph<int> G;
graph<int>::vertex_pointer a = G.add_vertex(1);
graph<int>::vertex_pointer b = G.add_vertex(2);
add_edge(a,b); //Compiler complains about this call
return 0;
}
 
J

Juha Nieminen

Mike said:
struct graph
{
friend edge_list& edges(vertex_pointer p){return p->second.edges;}

vertex_pointer add_vertex(VERTEX v)
{
V.push_back(make_pair(v, EDGE_LIST()));
vertex_pointer p = V.end();
return --p;
}

friend edge_pointer add_edge(vertex_pointer from, vertex_pointer
to, const EDGE& e=EDGE())
{
edges(from).push_back(make_pair(e,to));
edge_pointer p = edges(from).end();
return --p;
}
};

You have only declared those functions as friends, but you have not
declared the functions themselves in the outer scope. You need to add
those declarations to the global scope. In other words:

edge_list& edges(vertex_pointer p);
edge_pointer add_edge(vertex_pointer from, vertex_pointer to,
const EDGE& e=EDGE());
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,755
Messages
2,569,535
Members
45,007
Latest member
obedient dusk

Latest Threads

Top