templates and friends

G

Gianni Mariani

I have 2 distinct template classes which co-operate, hence are friends.
However, I can't seem to figure out what syntax to use to make this work.

What is the right(tm) way to write a friend class here ?

Here is the code:

template <typename A>
class Y;

template <typename A>
class X
{
friend class Y<A>;
private:

A m_a;

public:

X( A i_val );

template<typename B> void DoThing( Y<B> & b )
{
m_a = b.m_a;
}

};

template <typename A>
class Y
{
friend class X<A>;
private:

A m_a;

public:

Y( A i_val );

template<typename B> void DoOtherThing( Y<B> & b )
{
m_a = b.m_a;
}

};



int main()
{

Y<int> yi( 1 );
X<short> xs( 2 );

xs.DoThing( yi );

}

Here is the error:

g++ -c -o testfriend.o testfriend.cpp
testfriend.cpp: In member function `void X<A>::DoThing(Y<B>&) [with B =
int, A
= short int]':
testfriend.cpp:52: instantiated from here
testfriend.cpp:31: error: `int Y<int>::m_a' is private
testfriend.cpp:20: error: within this context
make: *** [testfriend.o] Error 1
 
J

John Harrison

Gianni Mariani said:
I have 2 distinct template classes which co-operate, hence are friends.
However, I can't seem to figure out what syntax to use to make this work.

What is the right(tm) way to write a friend class here ?

Here is the code:

template <typename A>
class Y;

template <typename A>
class X
{
friend class Y<A>;
private:

A m_a;

public:

X( A i_val );

template<typename B> void DoThing( Y<B> & b )
{
m_a = b.m_a;
}

};

template <typename A>
class Y
{
friend class X<A>;
private:

A m_a;

public:

Y( A i_val );

template<typename B> void DoOtherThing( Y<B> & b )
{
m_a = b.m_a;
}

};



int main()
{

Y<int> yi( 1 );
X<short> xs( 2 );

xs.DoThing( yi );

}

Here is the error:

g++ -c -o testfriend.o testfriend.cpp
testfriend.cpp: In member function `void X<A>::DoThing(Y<B>&) [with B =
int, A
= short int]':
testfriend.cpp:52: instantiated from here
testfriend.cpp:31: error: `int Y<int>::m_a' is private
testfriend.cpp:20: error: within this context
make: *** [testfriend.o] Error 1

You have to distinguish between

1) All template instances are friends of each other, e.g. X<int> is a friend
of Y<double>

2) Only templates instantiated with the same type are friend of each other,
e.g. X<int> is a friend of Y<int> but not of Y<double>.

You want case 1, but the code you've written is for case 2. Try this

template <typename A>
class Y;

template <typename A>
class X
{
template <typename B>
friend class Y;

etc.

john
 

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,744
Messages
2,569,482
Members
44,900
Latest member
Nell636132

Latest Threads

Top