模板函数的前向声明
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
}
相关文章:
- C++:为什么允许在另一个函数中声明函数,而不允许在函数定义中声明?
- 在c++中在类外声明函数有什么好处
- 使用 #define 声明函数
- 在静态库中声明函数,在使用该相同库的应用程序中定义它
- 如何强制编译器在 C/C++ 本身中声明函数?
- 如果您只需要在 .h 文件中声明函数.cpp是否需要在 .h 文件中声明函数?
- C++:<sys/sysctl.h> 无法声明函数CTL_HW和HW_NCPU
- 尝试声明函数的局部变量,但得到范围错误
- 如何在C++模板中声明函数
- 如何在另一个文件的类中声明函数
- 使用非类型模板参数正向声明函数模板
- 在此范围错误中未声明函数错误
- 当我们不能声明函数内联(GCC 编译器)时?
- 未在此作用域中声明函数,即使存在头文件也是如此
- 无法声明函数中的模板类型别名
- 单个CPP文件中多次声明函数声明可以吗?
- 编译一个支持VBA中声明函数的dll
- 使用从外部参数包中获取的参数类型声明函数
- 使用类成员正确地声明函数
- 在函数内重新声明函数