Porkchop1414 - 11 months ago 106

C++ Question

I have a template class with a friend template function. I currently have the following code and it is working:

`template<class T>`

class Vector

{

public:

template<class U, class W>

friend Vector<U> operator*(const W lhs, const Vector<U>& rhs);

}

template<class U, class W>

Vector<U> operator*(const W lhs, const Vector<U>& rhs)

{

// Multiplication

}

I would prefer for my solution to have forward declaration of the friend function so that I can have the security benefits and one-to-one correspondence that it provides compared to my current method. I tried the following but keep running into errors.

`template<class T>`

class Vector;

template<class T, class W>

Vector<T> operator*(const W lhs, const Vector<T>& rhs);

template<class T>

class Vector

{

public:

friend Vector<T> (::operator*<>)(const W lhs, const Vector<T>& rhs);

}

template<class T, class W>

Vector<T> operator*(const W lhs, const Vector<T>& rhs)

{

// Multiplication

}

Answer Source

I think you almost had it. You just needed to make the function a single parameter template when you friend it. The following compiles on g++ 4.5 although since I can't test the instantiation with your test case I'm not 100% sure it will solve your real problem.

```
template<class T>
class Vector;
template<class T, class W>
Vector<T> operator*(const W lhs, const Vector<T>& rhs);
template<class T>
class Vector
{
public:
template<class W>
friend Vector<T> operator*(const W lhs, const Vector<T>& rhs);
};
template<class T, class W>
Vector<T> operator*(const W lhs, const Vector<T>& rhs)
{
// Multiplication
}
```