Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

problem with a function template returning a private nested class of a class template

0 views
Skip to first unread message

ym...@hotmail.com

unread,
Dec 27, 2008, 9:20:48 PM12/27/08
to
Hi,
I have a class template with two template arguments. It contains a
private nested class, and I want a non-member function to return an
instance of the nested class:

//-----------------------------------------------------------------
template<typename T1,typename T2> class A {
class B {};
};

template<typename T> typename A<T,T>::B func(T x){};

int main() {
A<int,int> aii;
A<double,double> add;
A<int,double> aid;
A<double,int> adi;
func(1);
return 0;
}
//----------------------------------------------------------------

(I created some instances of A with different types for testing).
Naturally I'm getting a 'class a<int, int>::B is private' error, but I
simply cannot succeed in making func a friend function of the class
template A. Each reference to func inside the class template A
(whether it's a friend declaration or the whole function definition)
causes either multiple ambiguous declarations of func, or an access
violation because the different instances of A are not friends of each
other (at least I think that's the reason).
Help will be appreciated.
Thanks

jason.c...@gmail.com

unread,
Dec 27, 2008, 10:14:05 PM12/27/08
to


You have 3 options:

1. Make the class public.

2. Make the function a member function.

3. Declare it as a friend, the syntax is:

template<typename T1,typename T2> class A {
class B {};

template<typename T> friend typename A<T,T>::B func(T x);
};

Note that that declares func<int> to be a friend of A<float,double>,
it's not completely strict about the types.

As for your access violation, that's not related to "friend". "Friend"
tells the compiler not to fail if the friend accesses a private/
protected member of a class, but it's inconsequential to accessing
memory outside of your program's boundaries.

Jason

ym...@hotmail.com

unread,
Dec 28, 2008, 5:43:50 AM12/28/08
to
On Dec 28, 5:14 am, "jason.cipri...@gmail.com"

This solves my problem, thanks!

0 new messages