Nested private class template as friend

I have the following code that does not compile on GCC 4.9 as well as GCC 5.1. And I can't figure out why. Sorry if this is a noob question, I'm kind of new to C ++ templates.

template<class T>class A
{
    template<class X>friend class B;
    struct C {};
};

template<class X>class B 
{
    template<class T>friend struct A<T>::C;
};

int main()
{
    A<int> a;
    B<float> b;
}

      

I am getting the following errors when compiling

root@localhost# g++-49 templatefriend.cpp
templatefriend.cpp: In instantiation of รขclass B<float>รข:
templatefriend.cpp:38:9:   required from here
templatefriend.cpp:27:9: error: รขstruct A<T>::Cรข is private
  struct C {};
     ^
templatefriend.cpp:31:1: error: within this context
 {
 ^

      

where does this compile if i remove the templates

class A
{
    friend class B;
    class C{};
};

class B
{
    friend class A::C;
};

int main()
{
    A a;
    B b;
}

      

Any help is appreciated, or if such a question has already been asked, please share the link.

+3


source to share


1 answer


The warning you get from clang in this case is a little helpful:

warning: dependent nested name specifier 'A<X>::' for friend class declaration is not supported

      

In other words, A :: C is type dependent, so it doesn't work (although I don't know where in the standard it is described.



I suspect that you actually want the ratio between A<T>

and B<T>

, where is the T

same (for example, A<int>

and B<int>

, but not A<char>

and B<float>

). If so, you can accomplish this using the same template parameter in your friend's declaration

template <typename T> class B;

template<class T>
class A {
    friend class B<T>;  // B of the same templated type is my friend
    struct C {};
};

template<class T>
class B {
    friend struct A<T>::C; // A::C of the same templated type is my friend
};

      

Another alternative is template <typename> class A;

inside B

, which will then also make a A::C

friend.

+2


source







All Articles