Implicit function template creation
I have the following code which I only figured out to practice function templates.
#include <iostream>
template <typename T>
T fun( const T &t ) { return t; }
struct A {
int dataf;
A( int a ) : dataf(a) { std::cout << "birth\n"; }
friend A fun( const A & );
};
int main(){
A a( 5 );
fun( a );
return 0;
}
Although I am getting the following error:
code.cc:(.text+0x32): undefined reference to `fun(A const&)'
collect2: ld returned 1 exit status
I understand class templates well, but I'm still confused about functional templates.
+3
source to share
2 answers
Normal functions are preferred over function templates during overloading. Declaring a free friend function inside A
is an exact match to call in main
. The declaration is all the compiler has to pick up, so it compiles fine, but the linker can't find the definition because, well, you never defined it.
0
source to share