Not able to declare a template friend function inside a template class

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



Hey,
I'm trying to declare a function template as a friend for a class which is already a template.
So the situation is something like,
Fraction.h:

    template<typename T>
    class Fraction{
        ...
        friend Fraction<T> operator + (Fraction<T> const &a, Fraction<T> const &b);
    }


Fraction.cpp:

    template<typename T>
    Fraction<T> operator+(Fraction<T> const &a, Fraction<T> const &b) {
        Fraction<T> frac(a.num * b.den + b.num * a.den, a.den * b.den);
        return frac;
    }


But I'm getting the following warning:

    warning: friend declaration ‘Fraction<T> operator+(const Fraction<T>&, const Fraction<T>&)’ declares a non-template function [-Wnon-template-friend]


Now, if I try to fix this by declaring my friend function as a template inside the class, following the example given in https://en.cppreference.com/w/cpp/language/friend 
(Section: Template Friend Operators, second example), my code would then look like:
Fraction.h

    template<typename T>
    class Fraction{
        ...
        friend Fraction<T> operator + <>(Fraction<T> const &a, Fraction<T> const &b);
    }


I'm getting three related errors that say:

    error: declaration of ‘operator+’ as non-function
    error: expected ‘;’ at end of member declaration
    error: expected unqualified-id before ‘<’ token

I'm not sure what the issue is considering I'm following the exact syntax given in cppreference.com. Is this a compiler issue? How do I resolve this?

Thanks,
Vishal Subramanyam (20CS10081)





[Index of Archives]     [Linux C Programming]     [Linux Kernel]     [eCos]     [Fedora Development]     [Fedora Announce]     [Autoconf]     [The DWARVES Debugging Tools]     [Yosemite Campsites]     [Yosemite News]     [Linux GCC]

  Powered by Linux