user5767811
user5767811

Reputation:

C++ templates with friend function and operator overloading

I have been adding c++ templates to an existing Operator overloading program, and now I'm getting these errors. I'm not able to rectify these errors, can anybody help me... Here's the code... I'm able to template on simple overloaded function but having problem on friend function.. *****************NOTE:(Updated) Code after Rectification... /PROGRAM TO DEMONSTRATE OPERATOR OVERLOADING/ #include

template <class T>
class OP 
{
    T x, y, z;

    public:

    void IN()
    {
        std::cout << "Enter three No's : ";
        std::cin >> x >> y >> z;
    }

    void OUT()
    {
        std::cout << std::endl << x << " " << y << " " << z;
    }
    void operator~();
    void operator+(int);                    //Can accept both one or two argument

    template<class TA>
    friend void operator++(OP<T>);             //Accept one arguments (Unary Operator);

    template<class TB>
    friend void operator-(OP<T>, int);     //Accept two arguments     (Binary Operator)

    template<class TC>
    friend void operator!=(OP&, char t);
};

template<class T>
void OP<T>::operator~() //Unary Member Operator
{
    std::cout << std::endl << " ~ (tilde)";
}

template<class T>
void OP<T>::operator+(int y)    //Binary Member Operator
{
    std::cout << std::endl << "Argument sent is " << y;
}

template<class T>
void operator-(OP<T> &a, int t) //Binary Friend Operator
{
    a.x= a.x-t;
    a.y= a.y-t;
    a.z= a.z-t;
}

template<class T>
void operator!=(OP<T> &q, char t)   //Binary Friend Operator
{
    std::cout << std::endl << "Char " << t; 
}

template<class T>
void operator++(OP<T> x)    //Unary Friend Operator
{
    std::cout << std::endl << "Friend Unary Operator";
}

int main()
{
    OP <int> n, m;
    n.IN();
    m.IN();
    m+1;
    n!='t';
    int a = 1;
    char r='r';
    ~n;         //Member Function (Unary)
    n-a;        //Member Function (Unary)
    operator-(m, a);    //Friend Function (Binary)
    operator++(m);  //Friend Function (Unary)
    n.OUT();
    m.OUT();
    std::cin.get();
    return 0;
}

The error is on all three friend function and the error is

Now my friend function is not able to access the private member...<<< Please tell me what I'm doing wrong...

Upvotes: 1

Views: 551

Answers (1)

Richard Hodges
Richard Hodges

Reputation: 69882

If you declare a friend function within a template class, you must either provide the definition within the template class definition, or redeclare it outside the template class.

Declaring it as a friend with in the template class does not declare that function in the enclosing scope.

Upvotes: 3

Related Questions