这似乎工作:为什么模板化的朋友函数似乎没有被暴露,如果它是在一个类中定义的?
template<class A> struct S {
template<class B> friend S<B> f(B);
};
template<class B> S<B> f(B) {return S<B>{};}
int main() {
f(5);
}
好了,让我们做一个看似纯粹的外观变化和f
定义移动到struct
的身体:
template<class A> struct S {
template<class B> friend S<B> f(B) {return S<B>{};}
};
int main() {
f(5);
}
突然编译开始失败:
prog.cpp: In function ‘int main()’:
prog.cpp:6:5: error: ‘f’ was not declared in this scope
f(5);
^
为什么模板朋友函数需要在类的外部定义才能在此代码段中工作?
是否有任何技巧可以让函数f
在类定义的主体中定义?
看看副本中的第二个答案,它比第一个答案好。 – SergeyA