【发布时间】:2017-02-03 18:33:36
【问题描述】:
换句话说,为什么编译得很好:
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
}
对于第二个代码 sn-p,编译器(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(){
据我了解,在第二个代码 sn-p 中,当声明 var 时,编译器应该解析 B 类声明,将朋友声明中使用的 Type 替换为 int,一切正常。我错过了什么?
编辑:下面的 cmets 指出第二个代码 sn-p 似乎可以使用 clang 和 Visual C++ 2015 正确编译
【问题讨论】:
-
仅供参考。它似乎用clang编译
-
它还可以使用 Visual C++ 2015 编译,您可以在这里尝试:webcompiler.cloudapp.net
-
适用于 clang 3.8 和 gcc 6.1.0 Demo