In C++, why isn't it possible to friend a template class member function using the template type of another class?

前端 未结 2 754
花落未央
花落未央 2021-02-05 04:59

In other words, why does this compile fine :

template
class A{
  public:
    void f();
};

class B{
  friend void A::f();
};

tem         


        
2条回答
  •  深忆病人
    2021-02-05 05:16

    An explicit instantiation of B before it is used in A::f() resolves this problem. I assume GCC tries an implicit instantiation of B in the definition of A::f(). But the definition of A::f() is not finished and GCC 'looses' the friend declaration. It looks like a compiler problem.

    template
    class A
    {
    public:
        void f();
    };
    
    template // B is now a templated class
    class B
    {
        friend void A::f(); // Friending is done using B templated type
    };
    
    template
    class B; // <= explicit instantiation, that works
    
    template<>
    void A::f()
    {
        B* var = new B();
    }
    

提交回复
热议问题