Search code examples
c++templatesfriend

How to define a friend template function of a template class outside of its declaration?


If I define the friend template function inside the template class declaration, as follows, it can compile.

#include <iostream>

template <typename T>
class X {
public:
    X(int i) : n(i) {}

private:
    T n;

    template <typename U> 
    friend void doStuff(const X<T>& x, const U& u)
    {
        std::cout << (x.n + u) << std::endl;
    }
};

int main()
{
    X<int> x(1);
    doStuff(x, 3);
    return 0;
}

But if I move the definition of doStuff() out of the class decalaration, just after the declaration of class X<>, as follows, it can't compile.

template <typename U>
template <typename T>
void doStuff(const X<T>& x, const U& u)
{
    std::cout << (x.n + u) << std::endl;
}

Neither does the following code.

template <typename U, typename T>
void doStuff(const X<T>& x, const U& u)
{
    std::cout << (x.n + u) << std::endl;
}

So how should I define the template function doStuff() outside the class declaration?

Thanks in advance.


Solution

  • Perhaps like this:

    template <typename T>
    class X {
    public:
        X(int i) : n(i) {}
    
    private:
        T n;
    
        template <typename U, typename V>
        friend void doStuff(const X<U>& x, const V& u);
    };
    
    template <typename U, typename V>
    void doStuff(const X<U>& x, const V& u)
    {
        std::cout << (x.n + u) << std::endl;
    }
    
    int main()
    {
        X<int> x(1);
        doStuff(x, 3);
        X<double> y(1.0);
        doStuff(y, 3.5);
    }