Marco A.
Marco A.

Reputation: 43662

LNK2019 - why unresolved external with template friend function

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.

Upvotes: 3

Views: 938

Answers (2)

Sebastian Hoffmann
Sebastian Hoffmann

Reputation: 11482

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.

Upvotes: 2

Henok G.
Henok G.

Reputation: 49

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.

Upvotes: 0

Related Questions