Friend of nested template class

Consider the following program below, which compiles without a hitch on MinGW GCC 4.8.1:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
template <typename T>
class Outer
{
    class Nested1 {};
    template <typename U>
    class Nested2
    {
        Nested1* n1;
        friend Nested1* func(const Nested2& n2)
        {
            return n2.n1;
        }
    };
    public:
        Nested2<int> n2;
        void f() { (void)func(n2); }
};

int main()
{
    Outer<int> test;
    test.f();
}

(Yes, I know, it doesn't do anything useful, but it's just an example)
Is there any way I can move the definition of func outside of the class?
I've tried just about everything, but nothing seems to compile.
(Note that I've already solved this by restructuring things a bit to get rid of the need to use a friend function, but I'm just wondering if there's a way to simply move the definition of that function outside of the class definition, without tinkering with the actual structure)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
template <class T> class Outer; //The class exists and it is a template

template <class T, class U> //there is a function template
typename Outer<T>::Nested1* //dependant name
func(
	const typename Outer<T>::template Nested2<U> & //the dependant name is a template
);

template <typename T>
struct Outer
{
	class Nested1 {};
	template <typename U>
		class Nested2
		{
			Nested1* n1;
			/*pick one declaration*/
			//a one to one friendship relationship
			friend Nested1* func<T,U>(const Nested2& n2);

			//a many to many friendship relationship (not sure about this one)
			friend Nested1* func<T>(const Nested2& n2);
		};
	public:
	Nested2<int> n2;
	void f() {
		func<T>(n2); //need to specify, `T' cannot be resolved
	}
};

int main()
{
	Outer<int> test;
	test.f();
}

//definition
template <class T, class U>
typename Outer<T>::Nested1* func(const typename Outer<T>::template Nested2<U> &n2)
{
	return n2.n1;
}


Alternative
9
10
11
12
        friend Nested1* func(const Nested2& n2)
        {
                #include "the_definition_of_the_function.this_is_not_a_header"
        }



Edit: didn't realize that I changed class Outer to struct Outer.
It gives
error: ‘template<class U> class Outer<int>::Nested2’ is private
in that case
Last edited on
Topic archived. No new replies allowed.