简体   繁体   中英

Forward Declaration of Template Function

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
}

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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM