6

我有一个带有朋友模板功能的模板类。我目前有以下代码,它正在工作:

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
}
4

1 回答 1

3

我想你几乎拥有它。您只需将函数设为一个参数模板即可。以下是在 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
}
于 2013-02-28T01:10:36.080 回答