换句话说,为什么编译正常:
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,无特殊标志)表示:
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,并且一切都应该正常工作。我缺少什么?
编辑:下面的评论指出第二个代码片段似乎可以使用 clang 和 Visual C++ 2015 正确编译
显式实例化B<int>
在它被用于之前A<int>::f()
解决了这个问题。我假设 GCC 尝试隐式实例化B<int>
在定义中A<int>::f()
。但定义A<int>::f()
尚未完成,GCC“失去”朋友声明。看起来像是编译器问题。
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>();
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)