On Sun, 13 Mar 2022, 15:45 Vishal Subramanyam, <me@xxxxxxxxxxxxxxxxxxxx> wrote: > 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); > You don't need to say <T> here, just call the class Fraction } > > > 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? No, you are using the syntax for an explicit specialization of an existing function template, which is what cppreference shows. But your example has no previous declaration that can be specialized. How do I resolve this? > 1) Use the first syntax (without the redundant <T>) and ignore the warning or disable it with -Wno-non-template-friend or, 2) declare a function template which you specialize in the class: template<typename T> class Fraction; template<typename T> Fraction<T> operator +(Fraction<T> const &a, Fraction<T> const &b); template<typename T> class Fraction{ ... friend Fraction<T> operator + <>(Fraction<T> const &a, Fraction<T> const &b); } or, 3) define it as a template: template<typename T> class Fraction{ ... template<typename U> friend Fraction<U> operator + (Fraction<U> const &a, Fraction<U> const &b); }; > Thanks, > Vishal Subramanyam (20CS10081) > >