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
}
In computer programming, a forward declaration is a declaration of an identifier (denoting an entity such as a type, a variable, a constant, or a function) for which the programmer has not yet given a complete definition.
To instantiate a template function explicitly, follow the template keyword by a declaration (not definition) for the function, with the function identifier followed by the template arguments. template float twice<float>( float original ); Template arguments may be omitted when the compiler can infer them.
Generally you would include forward declarations in a header file and then include that header file in the same way that iostream is included.
A forward declaration allows us to tell the compiler about the existence of an identifier before actually defining the identifier. In the case of functions, this allows us to tell the compiler about the existence of a function before we define the function's body.
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With