LNK2019 - why unresolved external with template friend function

£可爱£侵袭症+ 提交于 2021-02-19 03:37:08

问题


I don't get this error:

#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
}

Taken from http://msdn.microsoft.com/en-us/library/799kze2z(v=vs.80).aspx

Why does the error not show up if I comment out S< int > s ? I got that I need to declare the template argument list as well, but I don't see the connection between that templated structure and the f(a) call..

Another weird thing: if I comment out just the f(a) call (and I leave all the rest in place), it compiles again. I'm using MSVC2012.


回答1:


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);

Consider the following example:

template<class T>
struct S {
    friend void foo(int);
};

int main() {
    S<int> s;
    foo(42);
}

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.

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.




回答2:


as mentioned above the friend function f(T) needs to be template function. The compiler is expecting that when you instantiate f(T) in main.



来源:https://stackoverflow.com/questions/21142900/lnk2019-why-unresolved-external-with-template-friend-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!