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

前端 未结 2 749
花落未央
花落未央 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:19

    Specializing template class member function without specializing whole template class is special case when you are allowed to specialize non-template member function, so maybe GCC is confused, and I don't know the reasons, but somehow you can't declare friendship to specialized non-template member of template class. Temporary solution would be to specialize whole class template for this to work.

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

    Then, define A::f:

    For class B:

    void A::f(){
          B* var = new B();
          (void)(var);
    }
    

    For template class B:

    void A::f(){
          B* var = new B();
          (void)(var);
    }
    

    But I think Clang is right here, there should be no problems for such friend declaration. It's probably a bug in GCC.

提交回复
热议问题