gpt4 book ai didi

c++ - 模板函数的前向声明

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:41:17 25 4
gpt4 key购买 nike

我有一个带有友元模板函数的模板类。我目前有以下代码并且可以正常工作:

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
}

关于c++ - 模板函数的前向声明,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15125332/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com