我没有得到这个错误:
#include <iostream>
using namespace std;
// LNK2019f.cpp
// LNK2019 expected
template<class T>
void f(T) {}
template<class T>
struct S {
friend void f(T);
// try the folowing line instead
// friend void f<T>(T);
};
int main() {
S<int> s;
int a = 2;
f(a); // unresolved external
}
取自http://msdn.microsoft.com/en-us/library/799kze2z(v=vs.80).aspx
如果我注释掉 S< int > s 为什么错误没有出现?我知道我也需要声明模板参数列表,但我没有看到该模板化结构与 f(a) 调用之间的联系..
另一件奇怪的事情:如果我只注释掉 f(a) 调用(并且我保留所有其余部分),它会再次编译。我正在使用 MSVC2012。
最佳答案
错误发生是因为你的 friend 声明充当了另一个非模板化的函数声明f
功能。
为了告诉编译器它是一个模板函数,你必须这样声明它:
friend void f<T>(T);
考虑以下示例:
template<class T>
struct S {
friend void foo(int);
};
int main() {
S<int> s;
foo(42);
}
这将抛出一个链接器错误,提示未解析的外部符号 foo
这里。在这种情况下 foo
已声明但未通过友元声明定义。
如果我们现在注释掉 S<int> s;
我们现在得到的不是链接器而是编译器错误:'foo': identifier not found
,因为 foo
尚未宣布,因为S<int>
未编译。
关于c++ - LNK2019 - 为什么未解决外部与模板 friend 功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21142900/