簡體   English   中英

模板功能的前向聲明

[英]Forward Declaration of Template Function

我有一個帶有朋友模板功能的模板類。 我目前有以下代碼,它正在工作:

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
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM