Declare non-template friend function for template class outside the class

Viewed 496

The following non-template code works well:

struct A { };

struct B
{
    B() {}
    B(const A&) {}
    friend B operator+(const B&) { return B(); }    
};

B operator+(const B&);

int main()
{
    A a;
    B b;
    +b;
    +a;
}

But if I make classes in this code templated:

template <class T>
struct A { };

template <class T>
struct B
{
    B() {}
    B(const A<T>&) {}
    friend B operator+(const B&) { return B(); }    
};

template <class T>
B<T> operator+(const B<T>&); // not really what I want 

int main()
{
    A<int> a;
    B<int> b;
    +b;
    +a;
}

some kind of troubles appear:

error: no match for 'operator+' (operand type is 'A<int>')

Is it possible to declare non-template friend function for template class outside the class (as I did for non-template classes above)?

I can solve the problem by adding template operator for A<T> argument and call friend function inside, but it is not interesting.

UPD:

Another workaround (inspired by R Sahu's answer) is add friend declaration for class A:

template <class T>
struct A { 
    friend B<T> operator+(const B<T>&);
};

but this gives a warning, and I don't know how to fix it correctly.

2 Answers
Related