更新时间:2023-11-30 21:58:52
发生此错误是因为您的朋友声明充当另一个未模板化的 f
函数的函数声明.
The error occurs because your friend declaration acts as a function declaration of another non-templated f
function.
您必须像这样声明它,以便告诉编译器它是模板函数:
You have to declare it like this in order to tell the compiler that it is a template function:
friend void f<T>(T);
请考虑以下示例:
template<class T>
struct S {
friend void foo(int);
};
int main() {
S<int> s;
foo(42);
}
这将引发链接器错误,提示此处未解析的外部符号 foo
.在这种情况下,声明了 foo
,但未通过好友声明进行定义.
This will throw a linker error muttering about an unresolved external symbol foo
here. In this case foo
is declared but not defined through the friend declaration.
如果我们现在注释掉 S< int>s;
我们现在不是链接器,而是编译器错误:'foo':找不到标识符
,因为尚未将 foo
声明为S< int>
未编译.
If we now comment out S<int> s;
we now get not a linker but a compiler error: 'foo': identifier not found
, because foo
has not been declared, as S<int>
isnt compiled.