Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

implicit instantiation of function template

Tags:

c++

templates

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.

like image 982
yauser Avatar asked Apr 26 '26 15:04

yauser


1 Answers

Change the friend declaration to:

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

or to:

friend A fun<A>( const A & );
like image 161
David G Avatar answered Apr 28 '26 07:04

David G