public inbox for gcc-help@gcc.gnu.org
 help / color / mirror / Atom feed
* Not able to declare a template friend function inside a template class
@ 2022-03-13 15:44 Vishal Subramanyam
  2022-03-13 16:48 ` Jonathan Wakely
  0 siblings, 1 reply; 2+ messages in thread
From: Vishal Subramanyam @ 2022-03-13 15:44 UTC (permalink / raw)
  To: gcc-help

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)


^ permalink raw reply	[flat|nested] 2+ messages in thread

end of thread, other threads:[~2022-03-13 16:48 UTC | newest]

Thread overview: 2+ messages (download: mbox.gz / follow: Atom feed)
-- links below jump to the message on this page --
2022-03-13 15:44 Not able to declare a template friend function inside a template class Vishal Subramanyam
2022-03-13 16:48 ` Jonathan Wakely

This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox;
as well as URLs for read-only IMAP folder(s) and NNTP newsgroup(s).