-1
#include<iostream.h>
template<class T>
class myclass;

template<class T>
void f(myclass<T> &c);

template<class T>
class myclass
{
    private:
        T value;
    public:
        friend void f(myclass<T> &c);

    T getvalue()
    {
        return value;
    }
    void setvalue(T v)
    {
        value=v;
    }
};

template<class T>
void f(myclass<T> &c)
{
    cout<<endl<<"function called:\n";
    cout<<c.getvalue()<<endl;
}
int main()
{
    myclass<int> object;
    object.setvalue(6);
    f(object);
    return 0;
}

This code is regarding templates with friend functions. While running the code, I am getting the following error:

error:undefined reference to f(myclass &) in line 22

kindly suggest. thanks in advance.

ByteHamster
  • 4,884
  • 9
  • 38
  • 53
neha
  • 1
  • 1

2 Answers2

0

Declare the friend function like

friend void f<>(myclass<T> &c);

Also in "new" C++ header iostream shall be specified like

#include <iostream>

and you should use directive

using namespace std;

if you do not want to change the other code in the program.

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
0

You missed to specify the template in the friend declaration:

template<typename U>
friend void f(myclass<U> &c);

See a fully working sample here please.

πάντα ῥεῖ
  • 1
  • 13
  • 116
  • 190
  • but why is it required to specify different template argument U when we have used T in forward declaration....when we use T it shows error...why so? – neha Apr 12 '15 at 10:57
  • @neha _"when we use T it shows error...why so? "_ Because `T` is already used by the enclosing template class. – πάντα ῥεῖ Apr 12 '15 at 10:59