yauser
yauser

Reputation: 705

implicit instantiation of function template

I have the following code which I conceived solely in order 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;
}

Though I get the following error:

code.cc:(.text+0x32): undefined reference to `fun(A const&)'
collect2: ld returned 1 exit status

I understand well class templates, but I am still confused about function templates.

Upvotes: 3

Views: 425

Answers (2)

jrok
jrok

Reputation: 55395

Normal functions are prefered over function templates during overload resoulution. The declaration of a free friend function inside A is an exact match for the call in main. The declaration is all that compiler needs to pick it up, so it compiles fine, but the linker can't find a definition because, well, you never defined it.

Upvotes: 0

David G
David G

Reputation: 96790

Change the friend declaration to:

template <class T> friend T fun( const T & );

or to:

friend A fun<A>( const A & );

Upvotes: 6

Related Questions