Velocity Reviews

Velocity Reviews (http://www.velocityreviews.com/forums/index.php)
-   C++ (http://www.velocityreviews.com/forums/f39-c.html)
-   -   Friend function defined in class template is not in scope (http://www.velocityreviews.com/forums/t742114-friend-function-defined-in-class-template-is-not-in-scope.html)

Mike 01-16-2011 04:12 AM

Friend function defined in class template is not in scope
 
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< pair<EDGE, typename list<pair<VERTEX, EDGE_LIST>
>::iterator> > edges;

};

typedef list< pair<EDGE, typename list<pair<VERTEX, EDGE_LIST>
>::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;
}


Juha Nieminen 01-16-2011 08:13 AM

Re: Friend function defined in class template is not in scope
 
Mike <seabass_friday@gmx.com> wrote:
> 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());


All times are GMT. The time now is 12:35 AM.

Powered by vBulletin®. Copyright ©2000 - 2014, vBulletin Solutions, Inc.
SEO by vBSEO ©2010, Crawlability, Inc.