Search code examples
c++templatesfriend

Template Friend Function of a Template Class (Friend with More Parameters)


I can't get this to work:

template<std::size_t s, typename T>
class A;

template<std::size_t s, typename T, typename U>
A<s, T> operator *(U const lhs, A<s, T> const& rhs);

template<std::size_t s, typename T>
class A
{
    // Blabla
    
    template<typename U>
    friend A<s, T> operator * <>(U const lhs, A<s, T> const& rhs);
};

This fails to compile with the following error message:

invalid use of template-id 'operator * <>' in declaration of primary template.


Solution

  • Since there is an additional template parameter (compared to the template class parameters), it seems that one does not need to add the <> after the function name. In conclusion, this worked fine for me:

    template<std::size_t s, typename T>
    class A;
    
    template<std::size_t s, typename T, typename U>
    A<s, T> operator *(U const lhs, A<s, T> const& rhs);
    
    template<std::size_t s, typename T>
    class A
    {
        // Blabla
        
        template<typename U>
        friend A<s, T> operator *(U const lhs, A<s, T> const& rhs);
    };
    
    template<std::size_t s, typename T, typename U>
    A<s, T> operator *(U const lhs, A<s, T> const& rhs)
    {
        //BlaBla
    }