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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With