在C ++中,为什么不能使用另一个类的模板类型来与模板类成员函数成为朋友?

问题描述:

换句话说,为什么编译良好:

In other words, why does this compile fine :

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

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

template<>
void A<int>::f(){
  B* var = new B();
}

虽然不是:

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

template<typename Type> // B is now a templated class
class B{
  friend void A<Type>::f(); // Friending is done using B templated type
};

template<>
void A<int>::f(){
  B<int>* var = new B<int>(); // var is now declared using int as its templated type
}

对于第二个代码段,编译器(gcc 6.2,无特殊标志)表示:

For the second code snippet, compiler (gcc 6.2, no special flags) says:

main.cpp: In instantiation of ‘class B<int>’:
main.cpp:14:28:   required from here
main.cpp:9:15: error: prototype for ‘void A<int>::f()’ does not match any in class ‘A<int>’
   friend void A<Type>::f();
               ^~~~~~~
main.cpp:13:6: error: candidate is: void A<Type>::f() [with Type = int]
 void A<int>::f(){

据我了解,在第二个代码段中,在声明var时,编译器应解析B类声明,将int声明中使用的Type替换为int,一切正常.我想念什么?

As I understand it, in the second code snippet, when declaring var the compiler should parse B class declaration, replace the Type used in the friend declaration by int, and everything should work fine. What am I missing?

以下评论指出,第二个代码片段似乎可以使用clang和Visual C ++ 2015正确编译

EDIT : comments below have pointed out that the second code snippet seems to compile correctly with clang and Visual C++ 2015

A<int>::f()中使用B<int>之前的显式实例化B<int>解决了此问题.我假设GCC在A<int>::f()的定义中尝试B<int>的隐式实例化.但是A<int>::f()的定义尚未完成,GCC会松散"朋友声明.看起来像是编译器问题.

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

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

template<typename Type> // B is now a templated class
class B
{
    friend void A<Type>::f(); // Friending is done using B templated type
};

template
class B<int>; // <= explicit instantiation, that works

template<>
void A<int>::f()
{
    B<int>* var = new B<int>();
}