模板函数的前向声明

Forward Declaration of Template Function

本文关键字:声明 函数      更新时间:2023-10-16

我有一个模板类和一个友元模板函数。我目前有以下代码,它正在工作:

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
}

我更希望我的解决方案具有友元函数的前向声明,这样与我当前的方法相比,我可以获得它提供的安全性优势和一对一通信。我尝试了以下操作,但总是出错。

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
}

我想你就快成功了。您只需要在添加好友时将函数设置为单个参数模板即可。下面的代码在g++ 4.5上编译,但是因为我不能用你的测试用例测试实例化,所以我不能100%确定它能解决你的实际问题。

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
}